task.contribution.ts 47.4 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

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

import * as nls from 'vs/nls';
import * as Env from 'vs/base/common/flags';

import { TPromise, Promise } from 'vs/base/common/winjs.base';
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';
20
import { IDisposable, disposeAll } from 'vs/base/common/lifecycle';
E
Erich Gamma 已提交
21 22 23 24 25
import { EventEmitter, ListenerUnbind } from 'vs/base/common/eventEmitter';
import * as Builder from 'vs/base/browser/builder';
import * as Types from 'vs/base/common/types';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { match } from 'vs/base/common/glob';
A
tslint  
Alex Dima 已提交
26
import { setTimeout } from 'vs/base/common/platform';
A
tslint  
Alex Dima 已提交
27
import { TerminateResponse } from 'vs/base/common/processes';
E
Erich Gamma 已提交
28 29 30 31 32 33

import { Registry } from 'vs/platform/platform';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { SyncActionDescriptor } from 'vs/platform/actions/common/actions';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IEventService } from 'vs/platform/event/common/event';
34
import { IEditor } from 'vs/platform/editor/common/editor';
E
Erich Gamma 已提交
35 36 37 38 39 40
import { IMessageService } from 'vs/platform/message/common/message';
import { IMarkerService, MarkerStatistics } from 'vs/platform/markers/common/markers';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IConfigurationService, ConfigurationServiceEventTypes } from 'vs/platform/configuration/common/configuration';
import { IFileService, FileChangesEvent, FileChangeType, EventType as FileEventType } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
A
Alex Dima 已提交
41
import { IExtensionService } from 'vs/platform/extensions/common/extensions';
E
Erich Gamma 已提交
42 43 44 45

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

M
Martin Aeschlimann 已提交
46
import jsonContributionRegistry = require('vs/platform/jsonschemas/common/jsonContributionRegistry');
E
Erich Gamma 已提交
47 48 49 50
import { IJSONSchema } from 'vs/base/common/jsonSchema';

import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';

51 52 53
import { IWorkbenchActionRegistry, Extensions as WorkbenchActionExtensions } from 'vs/workbench/common/actionRegistry';
import { IStatusbarItem, IStatusbarRegistry, Extensions as StatusbarExtensions, StatusbarItemDescriptor, StatusbarAlignment }  from 'vs/workbench/browser/parts/statusbar/statusbar';
import { IQuickOpenRegistry, Extensions as QuickOpenExtensions, QuickOpenHandlerDescriptor } from 'vs/workbench/browser/quickopen';
E
Erich Gamma 已提交
54

55
import { IQuickOpenService } from 'vs/workbench/services/quickopen/common/quickOpenService';
E
Erich Gamma 已提交
56 57 58 59
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService';

import { SystemVariables } from 'vs/workbench/parts/lib/node/systemVariables';
A
tslint  
Alex Dima 已提交
60
import { ITextFileService, EventType } from 'vs/workbench/parts/files/common/files';
E
Erich Gamma 已提交
61 62
import { IOutputService, IOutputChannelRegistry, Extensions as OutputExt } from 'vs/workbench/parts/output/common/output';

63
import { ITaskSystem, ITaskSummary, ITaskRunResult, TaskError, TaskErrors, TaskConfiguration, TaskDescription, TaskSystemEvents } from 'vs/workbench/parts/tasks/common/taskSystem';
E
Erich Gamma 已提交
64
import { ITaskService, TaskServiceEvents } from 'vs/workbench/parts/tasks/common/taskService';
D
Dirk Baeumer 已提交
65
import { templates as taskTemplates } from 'vs/workbench/parts/tasks/common/taskTemplates';
E
Erich Gamma 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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

import { LanguageServiceTaskSystem, LanguageServiceTaskConfiguration }  from 'vs/workbench/parts/tasks/common/languageServiceTaskSystem';
import * as FileConfig  from 'vs/workbench/parts/tasks/node/processRunnerConfiguration';
import { ProcessRunnerSystem } from 'vs/workbench/parts/tasks/node/processRunnerSystem';
import { ProcessRunnerDetector }  from 'vs/workbench/parts/tasks/node/processRunnerDetector';

let $ = Builder.$;

class AbstractTaskAction extends Action {

	protected taskService: ITaskService;
	protected telemetryService: ITelemetryService;

	constructor(id:string, label:string, @ITaskService taskService:ITaskService,
		@ITelemetryService telemetryService: ITelemetryService) {

		super(id, label);
		this.taskService = taskService;
		this.telemetryService = telemetryService;
	}
}

class BuildAction extends AbstractTaskAction {
	public static ID = 'workbench.action.tasks.build';
	public static TEXT = nls.localize('BuildAction.label','Run Build Task');

	constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) {
		super(id, label, taskService, telemetryService);
	}

	public run(): Promise {
		return this.taskService.build();
	}
}

class TestAction extends AbstractTaskAction {
	public static ID = 'workbench.action.tasks.test';
	public static TEXT = nls.localize('TestAction.label','Run Test Task');

	constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) {
		super(id, label, taskService, telemetryService);
	}

	public run(): Promise {
		return this.taskService.runTest();
	}
}

class RebuildAction extends AbstractTaskAction {
	public static ID = 'workbench.action.tasks.rebuild';
	public static TEXT = nls.localize('RebuildAction.label', 'Run Rebuild Task');

	constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) {
		super(id, label, taskService, telemetryService);
	}

	public run(): Promise {
		return this.taskService.rebuild();
	}
}

class CleanAction extends AbstractTaskAction {
	public static ID = 'workbench.action.tasks.clean';
	public static TEXT = nls.localize('CleanAction.label', 'Run Clean Task');

	constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) {
		super(id, label, taskService, telemetryService);
	}

	public run(): Promise {
		return this.taskService.clean();
	}
}

class ConfigureTaskRunnerAction extends Action {

	public static ID = 'workbench.action.tasks.configureTaskRunner';
	public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', 'Configure Task Runner');

	private configurationService: IConfigurationService;
	private fileService: IFileService;

	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;
	private outputService: IOutputService;
	private messageService: IMessageService;
D
Dirk Baeumer 已提交
152
	private quickOpenService: IQuickOpenService;
E
Erich Gamma 已提交
153 154 155 156

	constructor(id: string, label: string, @IConfigurationService configurationService: IConfigurationService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService,
		@IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService,
D
Dirk Baeumer 已提交
157
		@IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService) {
E
Erich Gamma 已提交
158 159 160 161 162 163 164 165

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

169 170 171 172 173
	public run(event?:any): TPromise<IEditor> {
		if (!this.contextService.getWorkspace()) {
			this.messageService.show(Severity.Info, nls.localize('ConfigureTaskRunnerAction.noWorkspace', 'Tasks are only available on a workspace folder.'));
			return TPromise.as(undefined);
		}
E
Erich Gamma 已提交
174 175 176 177
		let sideBySide = !!(event && (event.ctrlKey || event.metaKey));
		return this.fileService.resolveFile(this.contextService.toResource('.vscode/tasks.json')).then((success) => {
			return success;
		}, (err:any) => {
178
			;
179
			return this.quickOpenService.pick(taskTemplates, { placeHolder: nls.localize('ConfigureTaskRunnerAction.quickPick.template', 'Select a Task Runner')}).then(selection => {
D
Dirk Baeumer 已提交
180 181
				if (!selection) {
					return undefined;
E
Erich Gamma 已提交
182 183
				}
				let contentPromise: TPromise<string>;
D
Dirk Baeumer 已提交
184
				if (selection.autoDetect) {
185 186
					this.outputService.showOutput(TaskService.OutputChannel);
					this.outputService.append(TaskService.OutputChannel, nls.localize('ConfigureTaskRunnerAction.autoDetecting', 'Auto detecting tasks for {0}', selection.id) + '\n');
D
Dirk Baeumer 已提交
187
					let detector = new ProcessRunnerDetector(this.fileService, this.contextService, new SystemVariables(this.editorService, this.contextService));
188
					contentPromise = detector.detect(false, selection.id).then((value) => {
D
Dirk Baeumer 已提交
189 190 191 192 193
						let config = value.config;
						if (value.stderr && value.stderr.length > 0) {
							value.stderr.forEach((line) => {
								this.outputService.append(TaskService.OutputChannel, line + '\n');
							});
194
							this.messageService.show(Severity.Warning, nls.localize('ConfigureTaskRunnerAction.autoDetect', 'Auto detecting the task system failed. Using default template. Consult the task output for details.'));
D
Dirk Baeumer 已提交
195 196
							return selection.content;
						} else if (config) {
197 198 199
							if (value.stdout && value.stdout.length > 0) {
								value.stdout.forEach(line => this.outputService.append(TaskService.OutputChannel, line + '\n'));
							}
D
Dirk Baeumer 已提交
200 201 202 203 204 205 206 207 208 209
							let content = JSON.stringify(config, null, '\t');
							content = [
								'{',
									'\t// See http://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;
						}
E
Erich Gamma 已提交
210
					});
D
Dirk Baeumer 已提交
211 212
				} else {
					contentPromise = TPromise.as(selection.content);
E
Erich Gamma 已提交
213
				}
D
Dirk Baeumer 已提交
214 215
				return contentPromise.then(content => {
					return this.fileService.createFile(this.contextService.toResource('.vscode/tasks.json'), content);
E
Erich Gamma 已提交
216 217 218
				});
			});
		}).then((stat) => {
D
Dirk Baeumer 已提交
219 220 221 222
			if (!stat) {
				return undefined;
			}
			// // (2) Open editor with configuration file
E
Erich Gamma 已提交
223 224 225 226 227
			return this.editorService.openEditor({
				resource: stat.resource,
				options: {
					forceOpen: true
				}
D
Dirk Baeumer 已提交
228
			}, sideBySide);
E
Erich Gamma 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
		}, (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."));
		});
	}
}

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);
	}
	public run(): Promise {
		if (this.closeFunction) {
			this.closeFunction();
		}
A
Alex Dima 已提交
249
		return TPromise.as(null);
E
Erich Gamma 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	}
}

class TerminateAction extends AbstractTaskAction {
	public static ID = 'workbench.action.tasks.terminate';
	public static TEXT = nls.localize('TerminateAction.label', 'Terminate Running Task');

	constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService) {
		super(id, label, taskService, telemetryService);
	}

	public run(): Promise {
		return this.taskService.isActive().then((active) => {
			if (active) {
				return this.taskService.terminate().then((response) => {
					if (response.success) {
						return;
					} else {
						return Promise.wrapError(nls.localize('TerminateAction.failed', 'Failed to terminate running task'));
					}
				});
			}
		});
	}
}

class ShowLogAction extends AbstractTaskAction {
	public static ID = 'workbench.action.tasks.showLog';
	public static TEXT = nls.localize('ShowLogAction.label', 'Show Task Log');

	private outputService: IOutputService;

	constructor(id: string, label: string, @ITaskService taskService:ITaskService, @ITelemetryService telemetryService: ITelemetryService,
		@IOutputService outputService:IOutputService) {

		super(id, label, taskService, telemetryService);
		this.outputService = outputService;
	}

	public run(): Promise {
		return this.outputService.showOutput(TaskService.OutputChannel);
	}
}

class RunTaskAction extends Action {

	public static ID = 'workbench.action.tasks.runTask';
	public static TEXT = nls.localize('RunTaskAction.label', "Run Task");
	private quickOpenService: IQuickOpenService;

	constructor(id: string, label: string, @IQuickOpenService quickOpenService:IQuickOpenService) {
		super(id, label);
		this.quickOpenService = quickOpenService;
	}

	public run(event?:any): Promise {
		this.quickOpenService.show('task ');
A
Alex Dima 已提交
307
		return TPromise.as(null);
E
Erich Gamma 已提交
308 309 310 311
	}
}


312
class StatusBarItem implements IStatusbarItem {
E
Erich Gamma 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335

	private quickOpenService: IQuickOpenService;
	private markerService: IMarkerService;
	private taskService:ITaskService;
	private outputService: IOutputService;

	private intervalToken: any;
	private activeCount: number;
	private static progressChars:string = '|/-\\';

	constructor(@IQuickOpenService quickOpenService:IQuickOpenService,
		@IMarkerService markerService:IMarkerService, @IOutputService outputService:IOutputService,
		@ITaskService taskService:ITaskService) {

		this.quickOpenService = quickOpenService;
		this.markerService = markerService;
		this.outputService = outputService;
		this.taskService = taskService;
		this.activeCount = 0;
	}

	public render(container: HTMLElement): IDisposable {

336
		let callOnDispose: IDisposable[] = [],
E
Erich Gamma 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
			element = document.createElement('div'),
			// icon = document.createElement('a'),
			progress = document.createElement('div'),
			label = document.createElement('a'),
			error = document.createElement('div'),
			warning = document.createElement('div'),
			info = document.createElement('div');

		Dom.addClass(element, 'task-statusbar-item');

		// dom.addClass(icon, 'task-statusbar-item-icon');
		// element.appendChild(icon);

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

		Dom.addClass(error, 'task-statusbar-item-label-error');
		error.innerHTML = '0';
		label.appendChild(error);

		Dom.addClass(warning, 'task-statusbar-item-label-warning');
		warning.innerHTML = '0';
		label.appendChild(warning);

		Dom.addClass(info, 'task-statusbar-item-label-info');
		label.appendChild(info);
		$(info).hide();

//		callOnDispose.push(dom.addListener(icon, 'click', (e:MouseEvent) => {
//			this.outputService.showOutput(TaskService.OutputChannel, e.ctrlKey || e.metaKey, true);
//		}));

374
		callOnDispose.push(Dom.addDisposableListener(label, 'click', (e:MouseEvent) => {
E
Erich Gamma 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
			this.quickOpenService.show('!');
		}));

		let updateStatus = (element:HTMLDivElement, stats:number): boolean => {
			if (stats > 0) {
				element.innerHTML = stats.toString();
				$(element).show();
				return true;
			} else {
				$(element).hide();
				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;
			updateStatus(info, stats.infos);
		};

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

401
		callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, () => {
E
Erich Gamma 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
			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();
			}
		}));

418
		callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (data:TaskServiceEventData) => {
E
Erich Gamma 已提交
419 420 421 422 423 424 425 426
			this.activeCount--;
			if (this.activeCount === 0) {
				$(progress).hide();
				clearInterval(this.intervalToken);
				this.intervalToken = null;
			}
		}));

427
		callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, () => {
E
Erich Gamma 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440
			if (this.activeCount !== 0) {
				$(progress).hide();
				if (this.intervalToken) {
					clearInterval(this.intervalToken);
					this.intervalToken = null;
				}
				this.activeCount = 0;
			}
		}));

		container.appendChild(element);

		return {
441 442 443
			dispose: () => {
				callOnDispose = disposeAll(callOnDispose);
			}
E
Erich Gamma 已提交
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
		};
	}
}

interface TaskServiceEventData {
	error?: any;
}

class TaskService extends EventEmitter implements ITaskService {
	public serviceId = ITaskService;
	public static SERVICE_ID: string = 'taskService';
	public static OutputChannel:string = 'Tasks';

	private modeService: IModeService;
	private configurationService: IConfigurationService;
	private markerService: IMarkerService;
	private outputService: IOutputService;
	private messageService: IMessageService;
	private fileService: IFileService;
	private telemetryService: ITelemetryService;
	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;
	private textFileService: ITextFileService;
	private eventService: IEventService;
	private modelService: IModelService;
A
Alex Dima 已提交
469
	private extensionService: IExtensionService;
D
Dirk Baeumer 已提交
470
	private quickOpenService: IQuickOpenService;
E
Erich Gamma 已提交
471 472 473 474

	private _taskSystemPromise: TPromise<ITaskSystem>;
	private _taskSystem: ITaskSystem;
	private taskSystemListeners: ListenerUnbind[];
D
Dirk Baeumer 已提交
475
	private clearTaskSystemPromise: boolean;
E
Erich Gamma 已提交
476 477 478 479 480 481 482 483 484

	private fileChangesListener: ListenerUnbind;

	constructor(@IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService,
		@IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService,
		@IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService:IWorkbenchEditorService,
		@IFileService fileService:IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService:ITextFileService,
		@ILifecycleService lifecycleService: ILifecycleService, @IEventService eventService: IEventService,
A
Alex Dima 已提交
485
		@IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService,
D
Dirk Baeumer 已提交
486
		@IQuickOpenService quickOpenService: IQuickOpenService) {
E
Erich Gamma 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500

		super();
		this.modeService = modeService;
		this.configurationService = configurationService;
		this.markerService = markerService;
		this.outputService = outputService;
		this.messageService = messageService;
		this.editorService = editorService;
		this.fileService = fileService;
		this.contextService = contextService;
		this.telemetryService = telemetryService;
		this.textFileService = textFileService;
		this.eventService = eventService;
		this.modelService = modelService;
A
Alex Dima 已提交
501
		this.extensionService = extensionService;
D
Dirk Baeumer 已提交
502
		this.quickOpenService = quickOpenService;
E
Erich Gamma 已提交
503 504

		this.taskSystemListeners = [];
D
Dirk Baeumer 已提交
505
		this.clearTaskSystemPromise = false;
E
Erich Gamma 已提交
506 507
		this.configurationService.addListener(ConfigurationServiceEventTypes.UPDATED, () => {
			this.emit(TaskServiceEvents.ConfigChanged);
D
Dirk Baeumer 已提交
508 509 510 511 512 513
			if (this._taskSystem && this._taskSystem.isActiveSync()) {
				this.clearTaskSystemPromise = true;
			} else {
				this._taskSystem = null;
				this._taskSystemPromise = null;
			}
E
Erich Gamma 已提交
514 515 516 517 518 519 520 521 522 523 524
			this.disposeTaskSystemListeners();
		});

		lifecycleService.addBeforeShutdownParticipant(this);
	}

	private disposeTaskSystemListeners(): void {
		this.taskSystemListeners.forEach(unbind => unbind());
		this.taskSystemListeners = [];
	}

D
Dirk Baeumer 已提交
525
	private disposeFileChangesListener(): void {
E
Erich Gamma 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
		if (this.fileChangesListener) {
			this.fileChangesListener();
			this.fileChangesListener = null;
		}
	}

	private get taskSystemPromise(): TPromise<ITaskSystem> {
		if (!this._taskSystemPromise) {
			let variables = new SystemVariables(this.editorService, this.contextService);
			let clearOutput = true;
			this._taskSystemPromise = this.configurationService.loadConfiguration('tasks').then((config: TaskConfiguration) => {
				let parseErrors: string[] = config ? (<any>config).$parseErrors : null;
				if (parseErrors) {
					let isAffected = false;
					for (let i = 0; i < parseErrors.length; i++) {
						if (/tasks\.json$/.test(parseErrors[i])) {
							isAffected = true;
							break;
						}
					}
					if (isAffected) {
						this.outputService.append(TaskService.OutputChannel, nls.localize('TaskSystem.invalidTaskJson', 'Error: The content of the tasks.json file has syntax errors. Please correct them before executing a task.\n'));
I
isidor 已提交
548
						this.outputService.showOutput(TaskService.OutputChannel, true);
E
Erich Gamma 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
						return TPromise.wrapError({});
					}
				}
				let configPromise: TPromise<TaskConfiguration>;
				if (config) {
					if (this.isRunnerConfig(config) && this.hasDetectorSupport(<FileConfig.ExternalTaskRunnerConfiguration>config)) {
						let fileConfig = <FileConfig.ExternalTaskRunnerConfiguration>config;
						configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables, fileConfig).detect(true).then((value) => {
							clearOutput = this.printStderr(value.stderr);
							let detectedConfig = value.config;
							if (!detectedConfig) {
								return config;
							}
							let result: FileConfig.ExternalTaskRunnerConfiguration = Objects.clone(fileConfig);
							let configuredTasks: IStringDictionary<FileConfig.TaskDescription> = 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 result;
						});
					} else {
						configPromise = TPromise.as<TaskConfiguration>(config);
					}
				} else {
					configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, variables).detect(true).then((value) => {
						clearOutput = this.printStderr(value.stderr);
						return value.config;
					});
				}
				return configPromise.then((config) => {
					if (!config) {
						this._taskSystemPromise = null;
590
						throw new TaskError(Severity.Info, nls.localize('TaskSystem.noConfiguration', 'No task runner configured.'), TaskErrors.NotConfigured);
E
Erich Gamma 已提交
591 592 593 594 595 596 597 598 599
					}
					let result: ITaskSystem = null;
					if (config.buildSystem === 'service') {
						result = new LanguageServiceTaskSystem(<LanguageServiceTaskConfiguration>config, this.telemetryService, this.modeService);
					} else if (this.isRunnerConfig(config)) {
						result = new ProcessRunnerSystem(<FileConfig.ExternalTaskRunnerConfiguration>config, variables, this.markerService, this.modelService, this.telemetryService, this.outputService, TaskService.OutputChannel, clearOutput);
					}
					if (result === null) {
						this._taskSystemPromise = null;
600
						throw new TaskError(Severity.Info, nls.localize('TaskSystem.noBuildType', "No valid task runner configured. Supported task runners are 'service' and 'program'."), TaskErrors.NoValidTaskRunner);
E
Erich Gamma 已提交
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
					}
					this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Active, (event) => this.emit(TaskServiceEvents.Active, event)));
					this.taskSystemListeners.push(result.addListener(TaskSystemEvents.Inactive, (event) => this.emit(TaskServiceEvents.Inactive, event)));
					this._taskSystem = result;
					return result;
				}, (err: any) => {
					this.handleError(err);
					return Promise.wrapError(err);
				});
			});
		}
		return this._taskSystemPromise;
	}

	private printStderr(stderr: string[]): boolean {
		let result = true;
		if (stderr && stderr.length > 0) {
			stderr.forEach((line) => {
				result = false;
				this.outputService.append(TaskService.OutputChannel, line + '\n');
			});
I
isidor 已提交
622
			this.outputService.showOutput(TaskService.OutputChannel, true);
E
Erich Gamma 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
		}
		return result;
	}

	private isRunnerConfig(config: TaskConfiguration): boolean {
		return !config.buildSystem || config.buildSystem === 'program';
	}

	private hasDetectorSupport(config: FileConfig.ExternalTaskRunnerConfiguration): boolean {
		if (!config.command) {
			return false;
		}
		return ProcessRunnerDetector.supports(config.command);
	}

638 639 640
	public configureAction(): Action {
		return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT,
			this.configurationService, this.editorService, this.fileService, this.contextService,
D
Dirk Baeumer 已提交
641
			this.outputService, this.messageService, this.quickOpenService);
642 643
	}

E
Erich Gamma 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
	public build(): TPromise<ITaskSummary> {
		return this.executeTarget(taskSystem => taskSystem.build());
	}

	public rebuild(): TPromise<ITaskSummary> {
		return this.executeTarget(taskSystem => taskSystem.rebuild());
	}

	public clean(): TPromise<ITaskSummary> {
		return this.executeTarget(taskSystem => taskSystem.clean());
	}

	public runTest(): TPromise<ITaskSummary> {
		return this.executeTarget(taskSystem => taskSystem.runTest());
	}

660
	public run(taskIdentifier: string): TPromise<ITaskSummary> {
E
Erich Gamma 已提交
661 662 663
		return this.executeTarget(taskSystem => taskSystem.run(taskIdentifier));
	}

664
	private executeTarget(fn: (taskSystem: ITaskSystem) => ITaskRunResult): TPromise<ITaskSummary> {
E
Erich Gamma 已提交
665 666 667 668 669 670 671
		return this.textFileService.saveAll().then((value) => {
			return this.taskSystemPromise.
				then((taskSystem) => {
					return taskSystem.isActive().then((active) => {
						if (!active) {
							return fn(taskSystem);
						} else {
672
							throw new TaskError(Severity.Warning, nls.localize('TaskSystem.active', 'There is an active running task right now. Terminate it first before executing another task.'), TaskErrors.RunningTask);
E
Erich Gamma 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
						}
					});
				}).
				then((runResult: ITaskRunResult) => {
					if (runResult.restartOnFileChanges) {
						let pattern = runResult.restartOnFileChanges;
						this.fileChangesListener = this.eventService.addListener(FileEventType.FILE_CHANGES, (event: FileChangesEvent) => {
							let needsRestart = event.changes.some((change) => {
								return (change.type === FileChangeType.ADDED || change.type === FileChangeType.DELETED) && !!match(pattern, change.resource.fsPath);
							});
							if (needsRestart) {
								this.terminate().done(() => {
									// We need to give the child process a change to stop.
									setTimeout(() => {
										this.executeTarget(fn);
A
tslint  
Alex Dima 已提交
688
									}, 2000);
E
Erich Gamma 已提交
689 690 691 692
								});
							}
						});
					}
D
Dirk Baeumer 已提交
693 694 695 696 697 698 699
					return runResult.promise.then((value) => {
						if (this.clearTaskSystemPromise) {
							this._taskSystemPromise = null;
							this.clearTaskSystemPromise = false;
						}
						return value;
					});
E
Erich Gamma 已提交
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
				}, (err: any) => {
					this.handleError(err);
				});
		});
	}

	public isActive(): TPromise<boolean> {
		if (this._taskSystemPromise) {
			return this.taskSystemPromise.then(taskSystem => taskSystem.isActive());
		}
		return TPromise.as(false);
	}

	public terminate(): TPromise<TerminateResponse> {
		if (this._taskSystemPromise) {
			return this.taskSystemPromise.then(taskSystem => {
					return taskSystem.terminate();
				}).then(response => {
					if (response.success) {
D
Dirk Baeumer 已提交
719 720 721 722
						if (this.clearTaskSystemPromise) {
							this._taskSystemPromise = null;
							this.clearTaskSystemPromise = false;
						}
E
Erich Gamma 已提交
723
						this.emit(TaskServiceEvents.Terminated, {});
D
Dirk Baeumer 已提交
724
						this.disposeFileChangesListener();
E
Erich Gamma 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737
					}
					return response;
				});
		}
		return TPromise.as( { success: true} );
	}

	public tasks(): TPromise<TaskDescription[]> {
		return this.taskSystemPromise.then(taskSystem => taskSystem.tasks());
	}

	public beforeShutdown(): boolean | TPromise<boolean> {
		if (this._taskSystem && this._taskSystem.isActiveSync()) {
D
Dirk Baeumer 已提交
738
			if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({
E
Erich Gamma 已提交
739
				message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'),
740
				primaryButton: nls.localize('TaskSystem.terminateTask', "&&Terminate Task")
E
Erich Gamma 已提交
741 742 743 744 745
			})) {
				return this._taskSystem.terminate().then((response) => {
					if (response.success) {
						this.emit(TaskServiceEvents.Terminated, {});
						this._taskSystem = null;
D
Dirk Baeumer 已提交
746
						this.disposeFileChangesListener();
E
Erich Gamma 已提交
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
						this.disposeTaskSystemListeners();
						return false; // no veto
					}
					return true; // veto
				}, (err) => {
					return true; // veto
				});
			} else {
				return true; // veto
			}
		}
		return false; // Nothing to do here
	}

	private handleError(err:any):void {
		let showOutput = true;
		if (err instanceof TaskError) {
			let buildError = <TaskError>err;
765 766 767
			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 已提交
768
				let closeAction = new CloseMessageAction();
769
				let action = needsConfig
770
					? this.configureAction()
E
Erich Gamma 已提交
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
					: new TerminateAction(TerminateAction.ID, TerminateAction.TEXT, this, this.telemetryService);

				closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [closeAction, action ] });
			} 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) {
I
isidor 已提交
786
			this.outputService.showOutput(TaskService.OutputChannel, true);
E
Erich Gamma 已提交
787 788 789 790 791 792 793 794 795 796 797 798 799 800
		}
	}
}

export class TaskServiceParticipant implements IWorkbenchContribution {
	constructor(@IInstantiationService private instantiationService: IInstantiationService) {
		// Force loading the language worker service
		this.instantiationService.getInstance(ITaskService);
	}
	public getId(): string {
		return 'vs.taskService';
	}
}

801 802 803
let tasksCategory = nls.localize('tasksCategory', "Tasks");
let workbenchActionsRegistry = <IWorkbenchActionRegistry>Registry.as(WorkbenchActionExtensions.WorkbenchActions);
workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ConfigureTaskRunnerAction, ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT), tasksCategory);
E
Erich Gamma 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
if (Env.enableTasks) {

	// Task Service
	registerSingleton(ITaskService, TaskService);

	// Actions
	workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(BuildAction, BuildAction.ID, BuildAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_B }), tasksCategory);
	workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TestAction, TestAction.ID, TestAction.TEXT, { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_T }), tasksCategory);
	// workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RebuildAction, RebuildAction.ID, RebuildAction.TEXT), tasksCategory);
	// workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(CleanAction, CleanAction.ID, CleanAction.TEXT), tasksCategory);
	workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(TerminateAction, TerminateAction.ID, TerminateAction.TEXT), tasksCategory);
	workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(ShowLogAction, ShowLogAction.ID, ShowLogAction.TEXT), tasksCategory);
	workbenchActionsRegistry.registerWorkbenchAction(new SyncActionDescriptor(RunTaskAction, RunTaskAction.ID, RunTaskAction.TEXT), tasksCategory);

	// Register Quick Open
819 820
	(<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen)).registerQuickOpenHandler(
		new QuickOpenHandlerDescriptor(
E
Erich Gamma 已提交
821 822 823 824 825 826 827 828
			'vs/workbench/parts/tasks/browser/taskQuickOpen',
			'QuickOpenHandler',
			'task ',
			nls.localize('taskCommands', "Run Task")
		)
	);

	// Status bar
829 830
	let statusbarRegistry = <IStatusbarRegistry>Registry.as(StatusbarExtensions.Statusbar);
	statusbarRegistry.registerStatusbarItem(new StatusbarItemDescriptor(StatusBarItem, StatusbarAlignment.LEFT, 50 /* Medium Priority */));
E
Erich Gamma 已提交
831 832 833 834 835 836 837 838

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

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

	// tasks.json validation
839
	let schemaId = 'vscode://schemas/tasks';
E
Erich Gamma 已提交
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 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
	let schema : IJSONSchema =
		{
			'id': schemaId,
			'description': 'Task definition file',
			'type': 'object',
			'default': {
				'version': '0.1.0',
				'command': 'myCommand',
				'isShellCommand': false,
				'args': [],
				'showOutput': 'always',
				'tasks': [
					{
						'taskName': 'build',
						'showOutput': 'silent',
						'isBuildCommand': true,
						'problemMatcher': ['$tsc', '$lessCompile']
					}
				]
			},
			'definitions': {
				'showOutputType': {
					'type': 'string',
					'enum': ['always', 'silent', 'never'],
					'default': 'silent'
				},
				'patternType': {
					'anyOf': [
						{
							'type': 'string',
							'enum': ['$tsc', '$tsc-watch' ,'$msCompile', '$lessCompile', '$gulp-tsc', '$cpp', '$csc', '$vb', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']
						},
						{
							'$ref': '#/definitions/pattern'
						},
						{
							'type': 'array',
							'items': {
								'$ref': '#/definitions/pattern'
							}
						}
					]
				},
				'pattern': {
					'default': {
						'regexp': '^([^\\\\s].*)\\\\((\\\\d+,\\\\d+)\\\\):\\\\s*(.*)$',
						'file': 1,
						'location': 2,
						'message': 3
					},
					'additionalProperties': false,
					'properties': {
						'regexp': {
							'type': 'string',
							'description': nls.localize('JsonSchema.pattern.regexp', 'The regular expression to find an error, warning or info in the output.')
						},
						'file': {
							'type': 'integer',
							'description': nls.localize('JsonSchema.pattern.file', 'The match group index of the filename. If omitted 1 is used.')
						},
						'location': {
							'type': 'integer',
F
Francois Valdy 已提交
902
							'description': nls.localize('JsonSchema.pattern.location', 'The match group index of the problem\'s location. Valid location patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn). If omitted line and column is assumed.')
E
Erich Gamma 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
						},
						'line': {
							'type': 'integer',
							'description': nls.localize('JsonSchema.pattern.line', 'The match group index of the problem\'s line. Defaults to 2')
						},
						'column': {
							'type': 'integer',
							'description': nls.localize('JsonSchema.pattern.column', 'The match group index of the problem\'s column. Defaults to 3')
						},
						'endLine': {
							'type': 'integer',
							'description': nls.localize('JsonSchema.pattern.endLine', 'The match group index of the problem\'s end line. Defaults to undefined')
						},
						'endColumn': {
							'type': 'integer',
							'description': nls.localize('JsonSchema.pattern.endColumn', 'The match group index of the problem\'s end column. Defaults to undefined')
						},
						'severity': {
							'type': 'integer',
							'description': nls.localize('JsonSchema.pattern.severity', 'The match group index of the problem\'s severity. Defaults to undefined')
						},
						'code': {
							'type': 'integer',
							'description': nls.localize('JsonSchema.pattern.code', 'The match group index of the problem\'s code. Defaults to undefined')
						},
						'message': {
							'type': 'integer',
							'description': nls.localize('JsonSchema.pattern.message', 'The match group index of the message. If omitted it defaults to 4 if location is specified. Otherwise it defaults to 5.')
						},
						'loop': {
							'type': 'boolean',
							'description': nls.localize('JsonSchema.pattern.loop', 'In a multi line matcher loop indicated whether this pattern is executed in a loop as long as it matches. Can only specified on a last pattern in a multi line pattern.')
						}
					}
				},
				'problemMatcherType': {
					'oneOf': [
						{
							'type': 'string',
							'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']
						},
						{
							'$ref': '#/definitions/problemMatcher'
						},
						{
							'type': 'array',
							'items': {
								'anyOf': [
									{
										'$ref': '#/definitions/problemMatcher'
									},
									{
										'type': 'string',
										'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish']
									}
								]
							}
						}
					]
				},
				'watchingPattern': {
					'type': 'object',
					'additionalProperties': false,
					'properties': {
						'regexp': {
							'type': 'string',
							'description': nls.localize('JsonSchema.watchingPattern.regexp', 'The regular expression to detect the begin or end of a watching task.')
						},
						'file': {
							'type': 'integer',
							'description': nls.localize('JsonSchema.watchingPattern.file', 'The match group index of the filename. Can be omitted.')
						},
					}
				},
				'problemMatcher': {
					'type': 'object',
					'additionalProperties': false,
					'properties': {
						'base': {
							'type': 'string',
							'enum': ['$tsc', '$tsc-watch', '$msCompile', '$lessCompile', '$gulp-tsc', '$jshint', '$jshint-stylish', '$eslint-compact', '$eslint-stylish'],
							'description': nls.localize('JsonSchema.problemMatcher.base', 'The name of a base problem matcher to use.')
						},
						'owner': {
							'type': 'string',
988
							'description': nls.localize('JsonSchema.problemMatcher.owner', 'The owner of the problem inside Code. Can be omitted if base is specified. Defaults to \'external\' if omitted and base is not specified.')
E
Erich Gamma 已提交
989 990 991 992
						},
						'severity': {
							'type': 'string',
							'enum': ['error', 'warning', 'info'],
D
Dirk Baeumer 已提交
993
							'description': nls.localize('JsonSchema.problemMatcher.severity', 'The default severity for captures problems. Is used if the pattern doesn\'t define a match group for severity.')
E
Erich Gamma 已提交
994
						},
D
Dirk Baeumer 已提交
995 996 997 998 999
						'applyTo': {
							'type': 'string',
							'enum': ['allDocuments', 'openDocuments', 'closedDocuments'],
							'description': nls.localize('JsonSchema.problemMatcher.applyTo', 'Controls if a problem reported on a text document is applied only to open, closed or all documents.')
						},
E
Erich Gamma 已提交
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
						'pattern': {
							'$ref': '#/definitions/patternType',
							'description': nls.localize('JsonSchema.problemMatcher.pattern', 'A problem pattern or the name of a predefined problem pattern. Can be omitted if base is specified.')
						},
						'fileLocation': {
							'oneOf': [
								{
									'type': 'string',
									'enum': ['absolute', 'relative']
								},
								{
									'type': 'array',
									'items': {
										'type': 'string'
									}
								}
							],
							'description': nls.localize('JsonSchema.problemMatcher.fileLocation', 'Defines how file names reported in a problem pattern should be interpreted.')
						},
						'watching': {
							'type': 'object',
							'additionalProperties': false,
							'properties': {
								'activeOnStart': {
									'type': 'boolean',
									'description': nls.localize('JsonSchema.problemMatcher.watching.activeOnStart', 'If set to true the watcher is in active mode when the task starts. This is equals of issuing a line that matches the beginPattern')
								},
								'beginsPattern': {
									'oneOf': [
										{
											'type': 'string'
										},
										{
											'type': '#/definitions/watchingPattern'
										}
									],
									'description': nls.localize('JsonSchema.problemMatcher.watching.beginsPattern', 'If matched in the output the start of a watching task is signaled.')
								},
								'endsPattern': {
									'oneOf': [
										{
											'type': 'string'
										},
										{
											'type': '#/definitions/watchingPattern'
										}
									],
									'description': nls.localize('JsonSchema.problemMatcher.watching.endsPattern', 'If matched in the output the end of a watching task is signaled.')
								}
							}
						},
						'watchedTaskBeginsRegExp': {
							'type': 'string',
							'description': nls.localize('JsonSchema.problemMatcher.watchedBegin', 'A regular expression signaling that a watched tasks begins executing triggered through file watching.')
						},
						'watchedTaskEndsRegExp': {
							'type': 'string',
							'description': nls.localize('JsonSchema.problemMatcher.watchedEnd', 'A regular expression signaling that a watched tasks ends executing.')
						}
					}
				},
				'baseTaskRunnerConfiguration': {
					'type': 'object',
					'properties': {
						'command': {
							'type': 'string',
							'description': nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.')
						},
						'isShellCommand': {
							'type': 'boolean',
							'default': true,
1071
							'description': nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.')
E
Erich Gamma 已提交
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
						},
						'args': {
							'type': 'array',
							'description': nls.localize('JsonSchema.args', 'Additional arguments passed to the command.'),
							'items': {
								'type': 'string'
							}
						},
						'options': {
							'type': 'object',
							'description': nls.localize('JsonSchema.options', 'Additional command options'),
							'properties': {
								'cwd': {
									'type': 'string',
1086
									'description': nls.localize('JsonSchema.options.cwd', 'The current working directory of the executed program or script. If omitted Code\'s current workspace root is used.')
E
Erich Gamma 已提交
1087 1088 1089
								},
								'env': {
									'type': 'object',
1090 1091 1092
									'additionalProperties': {
										'type': 'string'
									},
E
Erich Gamma 已提交
1093 1094 1095 1096 1097 1098 1099 1100 1101
									'description': nls.localize('JsonSchema.options.env', 'The environment of the executed program or shell. If omitted the parent process\' environment is used.')
								}
							},
							'additionalProperties': {
								'type': ['string', 'array', 'object']
							}
						},
						'showOutput': {
							'$ref': '#/definitions/showOutputType',
1102
							'description': nls.localize('JsonSchema.showOutput', 'Controls whether the output of the running task is shown or not. If omitted \'always\' is used.')
E
Erich Gamma 已提交
1103 1104 1105 1106 1107 1108
						},
						'isWatching': {
							'type': 'boolean',
							'description': nls.localize('JsonSchema.watching', 'Whether the executed task is kept alive and is watching the file system.'),
							'default': true
						},
D
Dirk Baeumer 已提交
1109 1110 1111 1112 1113
						'promptOnClose': {
							'type': 'boolean',
							'description': nls.localize('JsonSchema.promptOnClose', 'Whether the user is prompted when VS Code closes with a running background task.'),
							'default': false
						},
E
Erich Gamma 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
						'echoCommand': {
							'type': 'boolean',
							'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'),
							'default': true
						},
						'suppressTaskName': {
							'type': 'boolean',
							'description': nls.localize('JsonSchema.suppressTaskName', 'Controls whether the task name is added as an argument to the command. Default is false.'),
							'default': true
						},
						'taskSelector': {
							'type': 'string',
							'description': nls.localize('JsonSchema.taskSelector', 'Prefix to indicate that an argument is task.')
						},
						'problemMatcher': {
							'$ref': '#/definitions/problemMatcherType',
							'description': nls.localize('JsonSchema.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.')
						},
						'tasks': {
							'type': 'array',
							'description': nls.localize('JsonSchema.tasks', 'The task configurations. Usually these are enrichments of task already defined in the external task runner.'),
							'items': {
								'type': 'object',
								'$ref': '#/definitions/taskDescription'
							}
						}
					}
				},
				'taskDescription': {
					'type': 'object',
					'required': ['taskName'],
					'additionalProperties': false,
					'properties': {
						'taskName': {
							'type': 'string',
							'description': nls.localize('JsonSchema.tasks.taskName', "The task's name")
						},
						'args': {
							'type': 'array',
							'description': nls.localize('JsonSchema.tasks.args', 'Additional arguments passed to the command when this task is invoked.'),
							'items': {
								'type': 'string'
							}
						},
						'suppressTaskName': {
							'type': 'boolean',
							'description': nls.localize('JsonSchema.tasks.suppressTaskName', 'Controls whether the task name is added as an argument to the command. If omitted the globally defined value is used.'),
							'default': true
						},
						'showOutput': {
							'$ref': '#/definitions/showOutputType',
1165
							'description': nls.localize('JsonSchema.tasks.showOutput', 'Controls whether the output of the running task is shown or not. If omitted the globally defined value is used.')
E
Erich Gamma 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
						},
						'echoCommand': {
							'type': 'boolean',
							'description': nls.localize('JsonSchema.echoCommand', 'Controls whether the executed command is echoed to the output. Default is false.'),
							'default': true
						},
						'isWatching': {
							'type': 'boolean',
							'description': nls.localize('JsonSchema.tasks.watching', 'Whether the executed task is kept alive and is watching the file system.'),
							'default': true
						},
						'isBuildCommand': {
							'type': 'boolean',
1179
							'description': nls.localize('JsonSchema.tasks.build', 'Maps this task to Code\'s default build command.'),
E
Erich Gamma 已提交
1180 1181 1182 1183
							'default': true
						},
						'isTestCommand': {
							'type': 'boolean',
1184
							'description': nls.localize('JsonSchema.tasks.test', 'Maps this task to Code\'s default test command.'),
E
Erich Gamma 已提交
1185 1186 1187 1188 1189 1190
							'default': true
						},
						'problemMatcher': {
							'$ref': '#/definitions/problemMatcherType',
							'description': nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.')
						}
D
Dirk Baeumer 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199
					},
					'defaultSnippets': [
						{
							'label': 'Empty task',
							'body': {
								'taskName': '{{taskName}}'
							}
						}
					]
E
Erich Gamma 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
				}
			},
			'allOf': [
				{
					'type': 'object',
					'required': ['version'],
					'properties': {
						'version': {
							'type': 'string',
							'enum': ['0.1.0'],
							'description': nls.localize('JsonSchema.version', 'The config\'s version number')
						},
						'windows': {
							'$ref': '#/definitions/baseTaskRunnerConfiguration',
							'description': nls.localize('JsonSchema.windows', 'Windows specific build configuration')
						},
						'osx': {
							'$ref': '#/definitions/baseTaskRunnerConfiguration',
							'description': nls.localize('JsonSchema.mac', 'Mac specific build configuration')
						},
						'linux': {
							'$ref': '#/definitions/baseTaskRunnerConfiguration',
							'description': nls.localize('JsonSchema.linux', 'Linux specific build configuration')
						}
					}
				},
				{
					'$ref': '#/definitions/baseTaskRunnerConfiguration'
				}
			]
		};
	let jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>Registry.as(jsonContributionRegistry.Extensions.JSONContribution);
	jsonRegistry.registerSchema(schemaId, schema);
	jsonRegistry.addSchemaFileAssociation('/.vscode/tasks.json', schemaId);
1234
}