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

'use strict';

import 'vs/css!./media/task.contribution';
import 'vs/workbench/parts/tasks/browser/taskQuickOpen';
10
import 'vs/workbench/parts/tasks/browser/terminateQuickOpen';
11
import 'vs/workbench/parts/tasks/browser/restartQuickOpen';
12 13
import 'vs/workbench/parts/tasks/browser/buildQuickOpen';
import 'vs/workbench/parts/tasks/browser/testQuickOpen';
E
Erich Gamma 已提交
14 15 16

import * as nls from 'vs/nls';

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

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

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

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

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

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

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

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

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

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

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

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

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

		super(id, label);
	}

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

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

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

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

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

E
Erich Gamma 已提交
234 235 236 237 238 239 240 241 242 243
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);
	}
244
	public run(): TPromise<void> {
E
Erich Gamma 已提交
245 246 247
		if (this.closeFunction) {
			this.closeFunction();
		}
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
		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 已提交
264 265 266
	}
}

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

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

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

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

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

296 297 298 299 300 301 302 303 304 305 306 307
	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 已提交
308

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

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

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

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

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

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

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

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

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

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

357
		let updateStatus = (element: HTMLDivElement, icon: HTMLDivElement, stats: number): boolean => {
E
Erich Gamma 已提交
358 359 360
			if (stats > 0) {
				element.innerHTML = stats.toString();
				$(element).show();
361
				$(icon).show();
E
Erich Gamma 已提交
362 363 364
				return true;
			} else {
				$(element).hide();
365
				$(icon).hide();
E
Erich Gamma 已提交
366 367 368 369 370 371 372 373
				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;
374
			updateStatus(info, infoIcon, stats.infos);
E
Erich Gamma 已提交
375 376 377 378 379 380
		};

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

A
Alex Dima 已提交
381
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Active, () => {
E
Erich Gamma 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
			this.activeCount++;
			if (this.activeCount === 1) {
				let index = 1;
				let chars = StatusBarItem.progressChars;
				progress.innerHTML = chars[0];
				this.intervalToken = setInterval(() => {
					progress.innerHTML = chars[index];
					index++;
					if (index >= chars.length) {
						index = 0;
					}
				}, 50);
				$(progress).show();
			}
		}));

A
Alex Dima 已提交
398
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Inactive, (data: TaskServiceEventData) => {
399 400 401 402 403 404 405 406 407 408 409
			// 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 已提交
410 411 412
			}
		}));

A
Alex Dima 已提交
413
		callOnDispose.push(this.taskService.addListener(TaskServiceEvents.Terminated, () => {
E
Erich Gamma 已提交
414 415 416 417 418 419 420 421 422 423 424 425
			if (this.activeCount !== 0) {
				$(progress).hide();
				if (this.intervalToken) {
					clearInterval(this.intervalToken);
					this.intervalToken = null;
				}
				this.activeCount = 0;
			}
		}));

		container.appendChild(element);

426 427
		this.updateStyles();

E
Erich Gamma 已提交
428
		return {
429
			dispose: () => {
J
Joao Moreno 已提交
430
				callOnDispose = dispose(callOnDispose);
431
			}
E
Erich Gamma 已提交
432 433 434 435 436 437 438 439
		};
	}
}

interface TaskServiceEventData {
	error?: any;
}

440
class NullTaskSystem extends EventEmitter implements ITaskSystem {
441
	public run(task: Task): ITaskExecuteResult {
442
		return {
443
			kind: TaskExecuteKind.Started,
444 445 446 447 448 449 450 451 452
			promise: TPromise.as<ITaskSummary>({})
		};
	}
	public isActive(): TPromise<boolean> {
		return TPromise.as(false);
	}
	public isActiveSync(): boolean {
		return false;
	}
453 454 455
	public getActiveTasks(): Task[] {
		return [];
	}
456 457 458
	public canAutoTerminate(): boolean {
		return true;
	}
459 460 461 462
	public terminate(task: string | Task): TPromise<TerminateResponse> {
		return TPromise.as<TerminateResponse>({ success: true });
	}
	public terminateAll(): TPromise<TerminateResponse> {
463 464 465 466
		return TPromise.as<TerminateResponse>({ success: true });
	}
}

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
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();
	}
}

504
interface WorkspaceTaskResult {
505
	set: TaskSet;
506 507 508
	annotatingTasks: {
		byIdentifier: IStringDictionary<Task>;
	};
509 510 511
	hasErrors: boolean;
}

512 513 514 515 516
interface WorkspaceConfigurationResult {
	config: TaskConfig.ExternalTaskRunnerConfiguration;
	hasErrors: boolean;
}

E
Erich Gamma 已提交
517
class TaskService extends EventEmitter implements ITaskService {
518

519
	// private static autoDetectTelemetryName: string = 'taskServer.autoDetect';
520
	private static RecentlyUsedTasks_Key = 'workbench.tasks.recentlyUsedTasks';
521

522
	public _serviceBrand: any;
E
Erich Gamma 已提交
523
	public static SERVICE_ID: string = 'taskService';
J
Johannes Rieken 已提交
524 525
	public static OutputChannelId: string = 'tasks';
	public static OutputChannelLabel: string = nls.localize('tasks', "Tasks");
E
Erich Gamma 已提交
526 527 528

	private modeService: IModeService;
	private configurationService: IConfigurationService;
D
Dirk Baeumer 已提交
529
	private configurationEditingService: IConfigurationEditingService;
E
Erich Gamma 已提交
530 531 532 533 534 535 536 537 538
	private markerService: IMarkerService;
	private outputService: IOutputService;
	private messageService: IMessageService;
	private fileService: IFileService;
	private telemetryService: ITelemetryService;
	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;
	private textFileService: ITextFileService;
	private modelService: IModelService;
A
Alex Dima 已提交
539
	private extensionService: IExtensionService;
D
Dirk Baeumer 已提交
540
	private quickOpenService: IQuickOpenService;
E
Erich Gamma 已提交
541

542
	private _configHasErrors: boolean;
543
	private _providers: Map<number, ITaskProvider>;
544 545

	private _workspaceTasksPromise: TPromise<WorkspaceTaskResult>;
546

E
Erich Gamma 已提交
547
	private _taskSystem: ITaskSystem;
548
	private _taskSystemListeners: IDisposable[];
549
	private _recentlyUsedTasks: LinkedMap<string, string>;
550

551
	private _outputChannel: IOutputChannel;
E
Erich Gamma 已提交
552

J
Johannes Rieken 已提交
553
	constructor( @IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService,
D
Dirk Baeumer 已提交
554
		@IConfigurationEditingService configurationEditingService: IConfigurationEditingService,
E
Erich Gamma 已提交
555
		@IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService,
J
Johannes Rieken 已提交
556 557 558
		@IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService: ITextFileService,
559
		@ILifecycleService lifecycleService: ILifecycleService,
A
Alex Dima 已提交
560
		@IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService,
561
		@IQuickOpenService quickOpenService: IQuickOpenService,
562
		@IEnvironmentService private environmentService: IEnvironmentService,
563
		@IConfigurationResolverService private configurationResolverService: IConfigurationResolverService,
564
		@ITerminalService private terminalService: ITerminalService,
565 566
		@IWorkbenchEditorService private workbenchEditorService: IWorkbenchEditorService,
		@IStorageService private storageService: IStorageService
567
	) {
E
Erich Gamma 已提交
568 569 570 571

		super();
		this.modeService = modeService;
		this.configurationService = configurationService;
D
Dirk Baeumer 已提交
572
		this.configurationEditingService = configurationEditingService;
E
Erich Gamma 已提交
573 574 575 576 577 578 579 580 581
		this.markerService = markerService;
		this.outputService = outputService;
		this.messageService = messageService;
		this.editorService = editorService;
		this.fileService = fileService;
		this.contextService = contextService;
		this.telemetryService = telemetryService;
		this.textFileService = textFileService;
		this.modelService = modelService;
A
Alex Dima 已提交
582
		this.extensionService = extensionService;
D
Dirk Baeumer 已提交
583
		this.quickOpenService = quickOpenService;
E
Erich Gamma 已提交
584

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

	private registerCommands(): void {
612
		CommandsRegistry.registerCommand('workbench.action.tasks.runTask', (accessor, arg) => {
613 614 615
			this.runTaskCommand(accessor, arg);
		});

616 617 618 619
		CommandsRegistry.registerCommand('workbench.action.tasks.restartTask', (accessor, arg) => {
			this.runRestartTaskCommand(accessor, arg);
		});

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
		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;
			}
635
			this.runBuildCommand();
636 637 638 639 640 641 642 643 644 645 646 647
		});

		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;
648
			}
649
			this.runTestCommand();
650
		});
E
Erich Gamma 已提交
651 652
	}

653
	private showOutput(): void {
654
		this._outputChannel.show(true);
655 656
	}

E
Erich Gamma 已提交
657
	private disposeTaskSystemListeners(): void {
658
		this._taskSystemListeners = dispose(this._taskSystemListeners);
E
Erich Gamma 已提交
659 660
	}

661 662 663 664
	public registerTaskProvider(handle: number, provider: ITaskProvider): void {
		if (!provider) {
			return;
		}
665
		this._providers.set(handle, provider);
666 667 668
	}

	public unregisterTaskProvider(handle: number): boolean {
669
		return this._providers.delete(handle);
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
	}

	public tasks(): TPromise<Task[]> {
		return this.getTaskSets().then((sets) => {
			let result: Task[] = [];
			for (let set of sets) {
				result.push(...set.tasks);
			}
			return result;
		});
	};

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

689 690 691 692 693 694 695
	public getActiveTasks(): TPromise<Task[]> {
		if (!this._taskSystem) {
			return TPromise.as([]);
		}
		return TPromise.as(this._taskSystem.getActiveTasks());
	}

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
	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);
	}
727

728 729
	public build(): TPromise<ITaskSummary> {
		return this.getTaskSets().then((values) => {
730
			let runnable = this.createRunnableTask(values, TaskGroup.Build);
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
			if (!runnable || !runnable.task) {
				throw new TaskError(Severity.Info, nls.localize('TaskService.noBuildTask', 'No build task defined. Mark a task with \'isBuildCommand\' in the tasks.json file.'), TaskErrors.NoBuildTask);
			}
			return this.executeTask(runnable.task, runnable.resolver);
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

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

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

	public runTest(): TPromise<ITaskSummary> {
		return this.getTaskSets().then((values) => {
751
			let runnable = this.createRunnableTask(values, TaskGroup.Test);
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
			if (!runnable || !runnable.task) {
				throw new TaskError(Severity.Info, nls.localize('TaskService.noTestTask', 'No test task defined. Mark a task with \'isTestCommand\' in the tasks.json file.'), TaskErrors.NoTestTask);
			}
			return this.executeTask(runnable.task, runnable.resolver);
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

	public run(task: string | Task): TPromise<ITaskSummary> {
		return this.getTaskSets().then((values) => {
			let resolver = this.createResolver(values);
			let requested: string;
			let toExecute: Task;
			if (Types.isString(task)) {
				requested = task;
				toExecute = resolver.resolve(task);
770
			} else {
771
				requested = task.name;
D
Dirk Baeumer 已提交
772
				toExecute = task;
773 774 775 776 777
			}
			if (!toExecute) {
				throw new TaskError(Severity.Info, nls.localize('TaskServer.noTask', 'Requested task {0} to execute not found.', requested), TaskErrors.TaskNotFound);
			} else {
				return this.executeTask(toExecute, resolver);
778
			}
779 780 781 782 783 784
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
	public getTasksForGroup(group: string): TPromise<Task[]> {
		return this.getTaskSets().then((values) => {
			let result: Task[] = [];
			for (let value of values) {
				for (let task of value.tasks) {
					if (task.group === group) {
						result.push(task);
					}
				}
			}
			return result;
		});
	}

	private splitTasks(tasks: Task[]): { configured: Task[], detected: Task[] } {
		let configured: Task[] = [];
		let detected: Task[] = [];
		for (let task of tasks) {
			if (task._source.kind === TaskSourceKind.Workspace) {
				configured.push(task);
			} else {
				detected.push(task);
			}
		}
		return { configured, detected };
	}

D
Dirk Baeumer 已提交
812 813 814 815 816 817 818 819 820 821
	public customize(task: Task, openConfig: boolean = false): TPromise<void> {
		if (task._source.kind !== TaskSourceKind.Extension) {
			return TPromise.as<void>(undefined);
		}
		let configuration = this.getConfiguration();
		if (configuration.hasParseErrors) {
			this.messageService.show(Severity.Warning, nls.localize('customizeParseErrors', 'The current task configuration has errors. Please fix the errors first before customizing a task.'));
			return TPromise.as<void>(undefined);
		}
		let fileConfig = configuration.config;
822 823 824 825
		let customize: TaskConfig.TaskDescription = { customize: task.identifier, taskName: task._label };
		if (task.problemMatchers === void 0) {
			customize.problemMatcher = [];
		}
D
Dirk Baeumer 已提交
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
		if (!fileConfig) {
			fileConfig = {
				version: '2.0.0',
				tasks: [customize]
			};
		} else {
			if (Array.isArray(fileConfig.tasks)) {
				fileConfig.tasks.push(customize);
			} else {
				fileConfig.tasks = [customize];
			}
		};
		return this.configurationEditingService.writeConfiguration(ConfigurationTarget.WORKSPACE, { key: 'tasks', value: fileConfig }).then(() => {
			if (openConfig) {
				let resource = this.contextService.toResource('.vscode/tasks.json');
				this.editorService.openEditor({
					resource: resource,
					options: {
						forceOpen: true,
						pinned: false
					}
				}, false);
			}
		});
	}

852
	private createRunnableTask(sets: TaskSet[], group: TaskGroup): { task: Task; resolver: ITaskResolver } {
853
		let uuidMap: IStringDictionary<Task> = Object.create(null);
D
Dirk Baeumer 已提交
854
		let labelMap: IStringDictionary<Task> = Object.create(null);
855 856
		let identifierMap: IStringDictionary<Task> = Object.create(null);

857 858
		let workspaceTasks: Task[] = [];
		let extensionTasks: Task[] = [];
859 860 861
		sets.forEach((set) => {
			set.tasks.forEach((task) => {
				uuidMap[task._id] = task;
862
				labelMap[task._label] = task;
863
				identifierMap[task.identifier] = task;
864
				if (group && task.group === group) {
865 866 867 868 869
					if (task._source.kind === TaskSourceKind.Workspace) {
						workspaceTasks.push(task);
					} else {
						extensionTasks.push(task);
					}
870
				}
871 872 873 874
			});
		});
		let resolver: ITaskResolver = {
			resolve: (id: string) => {
D
Dirk Baeumer 已提交
875
				return uuidMap[id] || labelMap[id] || identifierMap[id];
876 877
			}
		};
878 879 880 881 882 883 884 885 886 887 888 889
		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;
		}

		if (extensionTasks.length === 1) {
			return { task: extensionTasks[0], resolver };
890 891 892 893
		} else {
			let id: string = UUID.generateUuid();
			let task: Task = {
				_id: id,
894
				_source: { kind: TaskSourceKind.Generic, label: 'generic' },
895
				_label: id,
896 897
				name: id,
				identifier: id,
898
				dependsOn: extensionTasks.map(task => task._id),
899 900 901
				command: undefined,
			};
			return { task, resolver };
E
Erich Gamma 已提交
902 903 904
		}
	}

905
	private createResolver(sets: TaskSet[]): ITaskResolver {
D
Dirk Baeumer 已提交
906
		let labelMap: IStringDictionary<Task> = Object.create(null);
907 908 909 910
		let identifierMap: IStringDictionary<Task> = Object.create(null);

		sets.forEach((set) => {
			set.tasks.forEach((task) => {
911
				labelMap[task._label] = task;
912 913 914 915 916
				identifierMap[task.identifier] = task;
			});
		});
		return {
			resolve: (id: string) => {
D
Dirk Baeumer 已提交
917
				return labelMap[id] || identifierMap[id];
918
			}
919 920 921 922
		};
	}

	private executeTask(task: Task, resolver: ITaskResolver): TPromise<ITaskSummary> {
923 924 925 926 927 928 929 930 931 932
		return ProblemMatcherRegistry.onReady().then(() => {
			return this.textFileService.saveAll().then((value) => { // make sure all dirty files are saved
				let executeResult = this.getTaskSystem().run(task, resolver);
				if (executeResult.kind === TaskExecuteKind.Active) {
					let active = executeResult.active;
					if (active.same && active.background) {
						this.messageService.show(Severity.Info, nls.localize('TaskSystem.activeSame', 'The task is already active and in watch mode. To terminate the task use `F1 > terminate task`'));
					} else {
						throw new TaskError(Severity.Warning, nls.localize('TaskSystem.active', 'There is already a task running. Terminate it first before executing another task.'), TaskErrors.RunningTask);
					}
933
				}
934
				this.getRecentlyUsedTasks().set(task.identifier, task.identifier, Touch.First);
935 936
				return executeResult.promise;
			});
937 938 939
		});
	}

940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
	public restart(task: string | Task): void {
		if (!this._taskSystem) {
			return;
		}
		const id: string = Types.isString(task) ? task : task._id;
		this._taskSystem.terminate(id).then((response) => {
			if (response.success) {
				this.emit(TaskServiceEvents.Terminated, {});
				this.run(task);
			} else {
				this.messageService.show(Severity.Warning, nls.localize('TaskSystem.restartFailed', 'Failed to terminate and restart task {0}', Types.isString(task) ? task : task.name));
			}
			return response;
		});
	}

956
	public terminate(task: string | Task): TPromise<TerminateResponse> {
957 958 959
		if (!this._taskSystem) {
			return TPromise.as({ success: true });
		}
960 961
		const id: string = Types.isString(task) ? task : task._id;
		return this._taskSystem.terminate(id).then((response) => {
962 963 964
			if (response.success) {
				this.emit(TaskServiceEvents.Terminated, {});
			}
965 966 967 968 969 970 971 972 973
			return response;
		});
	}

	public terminateAll(): TPromise<TerminateResponse> {
		if (!this._taskSystem) {
			return TPromise.as({ success: true });
		}
		return this._taskSystem.terminateAll().then((response) => {
974 975 976 977 978 979 980 981 982 983 984 985 986 987
			this.emit(TaskServiceEvents.Terminated, {});
			return response;
		});
	}

	private getTaskSystem(): ITaskSystem {
		if (this._taskSystem) {
			return this._taskSystem;
		}
		let engine = this.getExecutionEngine();
		if (engine === ExecutionEngine.Terminal) {
			this._taskSystem = new TerminalTaskSystem(
				this.terminalService, this.outputService, this.markerService,
				this.modelService, this.configurationResolverService, this.telemetryService,
988
				this.workbenchEditorService,
989 990 991 992 993 994 995 996 997 998
				TaskService.OutputChannelId
			);
		} else {
			let system = new ProcessTaskSystem(
				this.markerService, this.modelService, this.telemetryService, this.outputService,
				this.configurationResolverService, TaskService.OutputChannelId,
			);
			system.hasErrors(this._configHasErrors);
			this._taskSystem = system;
		}
A
Alex Dima 已提交
999 1000
		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)));
1001 1002 1003 1004
		return this._taskSystem;
	}

	private getTaskSets(): TPromise<TaskSet[]> {
D
Dirk Baeumer 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
		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);
					}
				};
1022
				if (this.getJsonSchemaVersion() === JsonSchemaVersion.V2_0_0 && this._providers.size > 0) {
D
Dirk Baeumer 已提交
1023 1024 1025 1026 1027
					this._providers.forEach((provider) => {
						counter++;
						provider.provideTasks().done(done, error);
					});
				} else {
1028 1029
					resolve(result);
				}
D
Dirk Baeumer 已提交
1030
			});
1031 1032 1033 1034 1035 1036 1037 1038 1039
		}).then((result) => {
			return this.getWorkspaceTasks().then((workspaceTaskResult) => {
				let workspaceTasksToDelete: Task[] = [];
				let annotatingTasks = workspaceTaskResult.annotatingTasks;
				let legacyAnnotatingTasks = workspaceTaskResult.set ? this.getLegacyAnnotatingTasks(workspaceTaskResult.set) : undefined;
				if (annotatingTasks || legacyAnnotatingTasks) {
					for (let set of result) {
						for (let task of set.tasks) {
							if (annotatingTasks) {
1040
								let annotatingTask = annotatingTasks.byIdentifier[task.identifier];
1041 1042
								if (annotatingTask) {
									TaskConfig.mergeTasks(task, annotatingTask);
1043
									task.name = annotatingTask.name;
1044
									task._label = annotatingTask._label;
1045 1046 1047 1048 1049 1050 1051 1052 1053
									task._source.kind = TaskSourceKind.Workspace;
									continue;
								}
							}
							if (legacyAnnotatingTasks) {
								let legacyAnnotatingTask = legacyAnnotatingTasks[task.identifier];
								if (legacyAnnotatingTask) {
									TaskConfig.mergeTasks(task, legacyAnnotatingTask);
									task._source.kind = TaskSourceKind.Workspace;
1054
									task.name = legacyAnnotatingTask.name;
1055
									task._label = legacyAnnotatingTask._label;
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
									workspaceTasksToDelete.push(legacyAnnotatingTask);
									continue;
								}
							}
						}
					}
				}
				if (workspaceTaskResult.set) {
					if (workspaceTasksToDelete.length > 0) {
						let tasks = workspaceTaskResult.set.tasks;
						let newSet: TaskSet = {
							extension: workspaceTaskResult.set.extension,
							tasks: []
						};
						let toDelete = workspaceTasksToDelete.reduce<IStringDictionary<boolean>>((map, task) => {
							map[task._id] = true;
							return map;
						}, Object.create(null));
						newSet.tasks = tasks.filter(task => !toDelete[task._id]);
						result.push(newSet);
					} else {
						result.push(workspaceTaskResult.set);
					}
				}
				return result;
			}, () => {
				// If we can't read the tasks.json file provide at least the contributed tasks
				return result;
			});
1085 1086 1087
		});
	}

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
	private getLegacyAnnotatingTasks(workspaceTasks: TaskSet): IStringDictionary<Task> {
		let result: IStringDictionary<Task>;
		function getResult() {
			if (result) {
				return result;
			}
			result = Object.create(null);
			return result;
		}
		for (let task of workspaceTasks.tasks) {
			let commandName = task.command && task.command.name;
			// This is for backwards compatibility with the 0.1.0 task annotation code
			// if we had a gulp, jake or grunt command a task specification was a annotation
			if (commandName === 'gulp' || commandName === 'grunt' || commandName === 'jake') {
				getResult()[`${commandName}.${task.name}`] = task;
			}
		}
		return result;
	}

	private getWorkspaceTasks(): TPromise<WorkspaceTaskResult> {
1109 1110 1111
		if (this._workspaceTasksPromise) {
			return this._workspaceTasksPromise;
		}
1112
		this.updateWorkspaceTasks();
1113 1114 1115 1116 1117 1118
		return this._workspaceTasksPromise;
	}

	private updateWorkspaceTasks(): void {
		this._workspaceTasksPromise = this.computeWorkspaceTasks().then(value => {
			this._configHasErrors = value.hasErrors;
1119 1120 1121 1122
			if (this._taskSystem instanceof ProcessTaskSystem) {
				this._taskSystem.hasErrors(this._configHasErrors);
			}
			return value;
1123 1124 1125 1126
		});
	}

	private computeWorkspaceTasks(): TPromise<WorkspaceTaskResult> {
1127
		let configPromise: TPromise<WorkspaceConfigurationResult>;
1128 1129 1130
		{
			let { config, hasParseErrors } = this.getConfiguration();
			if (hasParseErrors) {
1131
				return TPromise.as({ set: undefined, hasErrors: true });
1132
			}
1133
			let engine = TaskConfig.ExecutionEngine._default;
1134
			if (config) {
1135
				engine = TaskConfig.ExecutionEngine.from(config);
1136 1137 1138 1139 1140 1141 1142
				if (engine === ExecutionEngine.Process) {
					if (this.hasDetectorSupport(config)) {
						configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService, config).detect(true).then((value): WorkspaceConfigurationResult => {
							let hasErrors = this.printStderr(value.stderr);
							let detectedConfig = value.config;
							if (!detectedConfig) {
								return { config, hasErrors };
1143
							}
1144 1145 1146 1147 1148
							let result: TaskConfig.ExternalTaskRunnerConfiguration = Objects.clone(config);
							let configuredTasks: IStringDictionary<TaskConfig.TaskDescription> = Object.create(null);
							if (!result.tasks) {
								if (detectedConfig.tasks) {
									result.tasks = detectedConfig.tasks;
1149
								}
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
							} else {
								result.tasks.forEach(task => configuredTasks[task.taskName] = task);
								detectedConfig.tasks.forEach((task) => {
									if (!configuredTasks[task.taskName]) {
										result.tasks.push(task);
									}
								});
							}
							return { config: result, hasErrors };
						});
					} else {
1161
						configPromise = TPromise.as({ config, hasErrors: false });
1162
					}
1163 1164 1165
				} else {
					configPromise = TPromise.as({ config, hasErrors: false });
				}
1166
			} else {
1167 1168 1169 1170 1171 1172 1173 1174
				if (engine === ExecutionEngine.Terminal) {
					configPromise = TPromise.as({ config, hasErrors: false });
				} else {
					configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService).detect(true).then((value) => {
						let hasErrors = this.printStderr(value.stderr);
						return { config: value.config, hasErrors };
					});
				}
1175 1176
			}
		}
1177
		return configPromise.then((resolved) => {
1178
			return ProblemMatcherRegistry.onReady().then((): WorkspaceTaskResult => {
1179
				if (!resolved || !resolved.config) {
1180
					return { set: undefined, annotatingTasks: undefined, hasErrors: resolved !== void 0 ? resolved.hasErrors : false };
1181
				}
1182
				let problemReporter = new ProblemReporter(this._outputChannel);
1183
				let parseResult = TaskConfig.parse(resolved.config, problemReporter);
1184 1185 1186 1187 1188 1189 1190
				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.'));
1191 1192
					return { set: undefined, annotatingTasks: undefined, hasErrors };
				}
1193
				let annotatingTasks: { byIdentifier: IStringDictionary<Task>; };
1194 1195
				if (parseResult.annotatingTasks && parseResult.annotatingTasks.length > 0) {
					annotatingTasks = {
1196
						byIdentifier: Object.create(null)
1197 1198
					};
					for (let task of parseResult.annotatingTasks) {
1199
						annotatingTasks.byIdentifier[task.customize] = task;
1200
					}
1201
				}
1202
				return { set: { tasks: parseResult.tasks }, annotatingTasks: annotatingTasks, hasErrors };
1203 1204 1205 1206 1207 1208 1209
			});
		});
	}

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

1215 1216 1217 1218 1219 1220 1221 1222
	private getJsonSchemaVersion(): JsonSchemaVersion {
		let { config } = this.getConfiguration();
		if (!config) {
			return JsonSchemaVersion.V2_0_0;
		}
		return TaskConfig.JsonSchemaVersion.from(config);
	}

1223 1224 1225
	private getConfiguration(): { config: TaskConfig.ExternalTaskRunnerConfiguration; hasParseErrors: boolean } {
		let result = this.configurationService.getConfiguration<TaskConfig.ExternalTaskRunnerConfiguration>('tasks');
		if (!result) {
1226
			return { config: undefined, hasParseErrors: false };
1227 1228 1229 1230 1231 1232 1233 1234 1235
		}
		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;
				}
1236
			}
1237
			if (isAffected) {
1238
				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'));
1239
				this.showOutput();
1240
				return { config: undefined, hasParseErrors: true };
1241
			}
1242 1243
		}
		return { config: result, hasParseErrors: false };
1244 1245
	}

E
Erich Gamma 已提交
1246
	private printStderr(stderr: string[]): boolean {
1247
		let result = false;
E
Erich Gamma 已提交
1248 1249
		if (stderr && stderr.length > 0) {
			stderr.forEach((line) => {
1250
				result = true;
1251
				this._outputChannel.append(line + '\n');
E
Erich Gamma 已提交
1252
			});
1253
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1254 1255 1256 1257
		}
		return result;
	}

1258
	public inTerminal(): boolean {
1259 1260 1261 1262
		if (this._taskSystem) {
			return this._taskSystem instanceof TerminalTaskSystem;
		}
		return this.getExecutionEngine() === ExecutionEngine.Terminal;
1263 1264
	}

1265
	private hasDetectorSupport(config: TaskConfig.ExternalTaskRunnerConfiguration): boolean {
E
Erich Gamma 已提交
1266 1267 1268 1269 1270 1271
		if (!config.command) {
			return false;
		}
		return ProcessRunnerDetector.supports(config.command);
	}

1272
	public configureAction(): Action {
1273
		return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT, this,
1274
			this.configurationService, this.editorService, this.fileService, this.contextService,
1275 1276
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService,
			this.extensionService);
1277 1278
	}

1279
	private configureBuildTask(): Action {
1280
		return new ConfigureBuildTaskAction(ConfigureBuildTaskAction.ID, ConfigureBuildTaskAction.TEXT, this,
1281
			this.configurationService, this.editorService, this.fileService, this.contextService,
1282 1283
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService,
			this.extensionService);
1284 1285
	}

E
Erich Gamma 已提交
1286
	public beforeShutdown(): boolean | TPromise<boolean> {
1287
		this.saveRecentlyUsedTasks();
E
Erich Gamma 已提交
1288
		if (this._taskSystem && this._taskSystem.isActiveSync()) {
D
Dirk Baeumer 已提交
1289
			if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({
E
Erich Gamma 已提交
1290
				message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'),
B
Benjamin Pasero 已提交
1291 1292
				primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task"),
				type: 'question'
E
Erich Gamma 已提交
1293
			})) {
1294
				return this._taskSystem.terminateAll().then((response) => {
E
Erich Gamma 已提交
1295 1296 1297 1298 1299
					if (response.success) {
						this.emit(TaskServiceEvents.Terminated, {});
						this._taskSystem = null;
						this.disposeTaskSystemListeners();
						return false; // no veto
D
Dirk Baeumer 已提交
1300 1301 1302
					} else if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
						return !this.messageService.confirm({
							message: nls.localize('TaskSystem.noProcess', 'The launched task doesn\'t exist anymore. If the task spawned background processes exiting VS Code might result in orphaned processes. To avoid this start the last background process with a wait flag.'),
B
Benjamin Pasero 已提交
1303 1304
							primaryButton: nls.localize({ key: 'TaskSystem.exitAnyways', comment: ['&& denotes a mnemonic'] }, "&&Exit Anyways"),
							type: 'info'
D
Dirk Baeumer 已提交
1305
						});
E
Erich Gamma 已提交
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
					}
					return true; // veto
				}, (err) => {
					return true; // veto
				});
			} else {
				return true; // veto
			}
		}
		return false; // Nothing to do here
	}

1318
	private getConfigureAction(code: TaskErrors): Action {
J
Johannes Rieken 已提交
1319
		switch (code) {
1320 1321 1322 1323 1324 1325
			case TaskErrors.NoBuildTask:
				return this.configureBuildTask();
			default:
				return this.configureAction();
		}
	}
1326

J
Johannes Rieken 已提交
1327
	private handleError(err: any): void {
E
Erich Gamma 已提交
1328 1329 1330
		let showOutput = true;
		if (err instanceof TaskError) {
			let buildError = <TaskError>err;
1331 1332 1333
			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 已提交
1334
				let closeAction = new CloseMessageAction();
1335
				let action: Action = needsConfig
1336
					? this.getConfigureAction(buildError.code)
1337 1338 1339 1340
					: new Action(
						'workbench.action.tasks.terminate',
						nls.localize('TerminateAction.label', "Terminate Running Task"),
						undefined, true, () => { this.runTerminateCommand(); return TPromise.as<void>(undefined); });
J
Johannes Rieken 已提交
1341
				closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [action, closeAction] });
E
Erich Gamma 已提交
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
			} 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) {
1354
			this._outputChannel.show(true);
E
Erich Gamma 已提交
1355 1356
		}
	}
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372

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

	private runTaskCommand(accessor: ServicesAccessor, arg: any): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (Types.isString(arg)) {
			this.tasks().then(tasks => {
				for (let task of tasks) {
D
Dirk Baeumer 已提交
1373
					if (task.identifier === arg) {
1374
						this.run(task);
1375 1376 1377 1378 1379 1380 1381 1382
					}
				}
			});
		} else {
			this.quickOpenService.show('task ');
		}
	}

1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
	private runBuildCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (!this.inTerminal()) {
			this.build();
			return;
		}
		this.getTasksForGroup(TaskGroup.Build).then((tasks) => {
			let { configured, detected } = this.splitTasks(tasks);
			let total = configured.length + detected.length;
			if (total === 0) {
				return;
			}
			if (total === 1) {
				this.run(configured[0] || detected[0]);
			} else {
				this.quickOpenService.show('build task ');
			}
		});
	}

	private runTestCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (!this.inTerminal()) {
			this.build();
			return;
		}
		this.getTasksForGroup(TaskGroup.Test).then((tasks) => {
			let { configured, detected } = this.splitTasks(tasks);
			let total = configured.length + detected.length;
			if (total === 0) {
				return;
			}
			if (total === 1) {
				this.run(configured[0] || detected[0]);
			} else {
				this.quickOpenService.show('test task ');
			}
		});
	}

1427 1428 1429 1430 1431
	private runTerminateCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (this.inTerminal()) {
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
					return;
				}
				if (activeTasks.length === 1) {
					this.terminate(activeTasks[0]);
				} else {
					this.quickOpenService.show('terminate task ');
				}
			});
1442 1443 1444
		} else {
			this.isActive().then((active) => {
				if (active) {
1445
					this.terminateAll().then((response) => {
1446
						if (response.success) {
1447 1448 1449
							return;
						}
						if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
1450 1451
							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 {
1452
							this.messageService.show(Severity.Error, nls.localize('TerminateAction.failed', 'Failed to terminate running task'));
1453 1454 1455 1456 1457 1458
						}
					});
				}
			});
		}
	}
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484

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

1487

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

1491 1492
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' } });
1493
MenuRegistry.addCommand({ id: 'workbench.action.tasks.restartTask', title: { value: nls.localize('RestartTaskAction.label', "Restart Task"), original: 'Restart Task' }, category: { value: tasksCategory, original: 'Tasks' } });
1494 1495 1496
MenuRegistry.addCommand({ id: 'workbench.action.tasks.terminate', title: { value: nls.localize('TerminateAction.label', "Terminate Running Task"), original: 'Terminate Running Task' }, category: { value: tasksCategory, original: 'Tasks' } });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.build', title: { value: nls.localize('BuildAction.label', "Run Build Task"), original: 'Run Build Task' }, category: { value: tasksCategory, original: 'Tasks' } });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.test', title: { value: nls.localize('TestAction.label', "Run Test Task"), original: 'Run Test Task' }, category: { value: tasksCategory, original: 'Tasks' } });
1497 1498
// 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 });
1499 1500 1501 1502 1503

// Task Service
registerSingleton(ITaskService, TaskService);

// Register Quick Open
1504 1505 1506
const quickOpenRegistry = (<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen));

quickOpenRegistry.registerQuickOpenHandler(
1507 1508 1509 1510
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/taskQuickOpen',
		'QuickOpenHandler',
		'task ',
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
		nls.localize('quickOpen.task', "Run Task")
	)
);

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

1524 1525 1526 1527 1528 1529 1530 1531 1532
quickOpenRegistry.registerQuickOpenHandler(
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/restartQuickOpen',
		'QuickOpenHandler',
		'restart task ',
		nls.localize('quickOpen.restartTask', "Restart Task")
	)
);

1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
quickOpenRegistry.registerQuickOpenHandler(
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/buildQuickOpen',
		'QuickOpenHandler',
		'build task ',
		nls.localize('quickOpen.buildTask', "Build Task")
	)
);

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

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

1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
// Status bar
let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar);
statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(StatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */));

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

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

// tasks.json validation
let schemaId = 'vscode://schemas/tasks';
D
Dirk Baeumer 已提交
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
let schema: IJSONSchema = {
	id: schemaId,
	description: 'Task definition file',
	type: 'object',
	default: {
		version: '0.1.0',
		command: 'myCommand',
		isShellCommand: false,
		args: [],
		showOutput: 'always',
		tasks: [
1577
			{
D
Dirk Baeumer 已提交
1578 1579 1580 1581
				taskName: 'build',
				showOutput: 'silent',
				isBuildCommand: true,
				problemMatcher: ['$tsc', '$lessCompile']
1582 1583
			}
		]
D
Dirk Baeumer 已提交
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
	}
};

import schemaVersion1 from './jsonSchema_v1';
import schemaVersion2 from './jsonSchema_v2';
schema.definitions = {
	...schemaVersion1.definitions,
	...schemaVersion2.definitions,
};
schema.oneOf = [...schemaVersion1.oneOf, ...schemaVersion2.oneOf];


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