task.contribution.ts 43.6 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*---------------------------------------------------------------------------------------------
 *  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 { 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';
J
Joao Moreno 已提交
19
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
20
import { EventEmitter } from 'vs/base/common/eventEmitter';
E
Erich Gamma 已提交
21 22 23
import * as Builder from 'vs/base/browser/builder';
import * as Types from 'vs/base/common/types';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
D
Dirk Baeumer 已提交
24
import { TerminateResponse, TerminateResponseCode } from 'vs/base/common/processes';
25
import * as strings from 'vs/base/common/strings';
26
import { ValidationStatus, ValidationState } from 'vs/base/common/parsers';
27
import * as UUID from 'vs/base/common/uuid';
E
Erich Gamma 已提交
28 29 30

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

E
Erich Gamma 已提交
45 46 47 48

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

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

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

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

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

67 68
import { ITerminalService } from 'vs/workbench/parts/terminal/common/terminal';

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

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

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

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

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

	private configurationService: IConfigurationService;
	private fileService: IFileService;

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

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

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

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

186 187 188 189 190 191 192 193
class ConfigureTaskRunnerAction extends OpenTaskConfigurationAction {
	public static ID = 'workbench.action.tasks.configureTaskRunner';
	public static TEXT = nls.localize('ConfigureTaskRunnerAction.label', "Configure Task Runner");

	constructor(id: string, label: string, @IConfigurationService configurationService: IConfigurationService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService, @IFileService fileService: IFileService,
		@IWorkspaceContextService contextService: IWorkspaceContextService, @IOutputService outputService: IOutputService,
		@IMessageService messageService: IMessageService, @IQuickOpenService quickOpenService: IQuickOpenService,
194 195
		@IEnvironmentService environmentService: IEnvironmentService,
		@IConfigurationResolverService configurationResolverService: IConfigurationResolverService) {
J
Johannes Rieken 已提交
196
		super(id, label, configurationService, editorService, fileService, contextService,
197
			outputService, messageService, quickOpenService, environmentService, configurationResolverService);
J
Johannes Rieken 已提交
198
	}
199 200 201 202 203 204 205 206 207 208 209

}

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

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

E
Erich Gamma 已提交
217 218 219 220 221 222 223 224 225 226
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);
	}
227
	public run(): TPromise<void> {
E
Erich Gamma 已提交
228 229 230
		if (this.closeFunction) {
			this.closeFunction();
		}
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
		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 已提交
247 248 249
	}
}

250
class StatusBarItem implements IStatusbarItem {
E
Erich Gamma 已提交
251

252
	private panelService: IPanelService;
E
Erich Gamma 已提交
253
	private markerService: IMarkerService;
J
Johannes Rieken 已提交
254
	private taskService: ITaskService;
E
Erich Gamma 已提交
255 256 257 258
	private outputService: IOutputService;

	private intervalToken: any;
	private activeCount: number;
J
Johannes Rieken 已提交
259
	private static progressChars: string = '|/-\\';
E
Erich Gamma 已提交
260

J
Johannes Rieken 已提交
261 262 263
	constructor( @IPanelService panelService: IPanelService,
		@IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService,
		@ITaskService taskService: ITaskService,
264
		@IPartService private partService: IPartService) {
E
Erich Gamma 已提交
265

266
		this.panelService = panelService;
E
Erich Gamma 已提交
267 268 269 270 271 272 273 274
		this.markerService = markerService;
		this.outputService = outputService;
		this.taskService = taskService;
		this.activeCount = 0;
	}

	public render(container: HTMLElement): IDisposable {

275
		let callOnDispose: IDisposable[] = [],
E
Erich Gamma 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
			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);
S
Sandeep Somavarapu 已提交
296
		element.title = nls.localize('problems', "Problems");
E
Erich Gamma 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309

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

J
Johannes Rieken 已提交
310 311 312
		//		callOnDispose.push(dom.addListener(icon, 'click', (e:MouseEvent) => {
		//			this.outputService.showOutput(TaskService.OutputChannel, e.ctrlKey || e.metaKey, true);
		//		}));
E
Erich Gamma 已提交
313

J
Johannes Rieken 已提交
314 315
		callOnDispose.push(Dom.addDisposableListener(label, 'click', (e: MouseEvent) => {
			const panel = this.panelService.getActivePanel();
316 317 318 319 320
			if (panel && panel.getId() === Constants.MARKERS_PANEL_ID) {
				this.partService.setPanelHidden(true);
			} else {
				this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
			}
J
Johannes Rieken 已提交
321
		}));
E
Erich Gamma 已提交
322

J
Johannes Rieken 已提交
323
		let updateStatus = (element: HTMLDivElement, stats: number): boolean => {
E
Erich Gamma 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
			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());
		});

346
		callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, () => {
E
Erich Gamma 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
			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();
			}
		}));

J
Johannes Rieken 已提交
363
		callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (data: TaskServiceEventData) => {
364 365 366 367 368 369 370 371 372 373 374
			// 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 已提交
375 376 377
			}
		}));

378
		callOnDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, () => {
E
Erich Gamma 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391
			if (this.activeCount !== 0) {
				$(progress).hide();
				if (this.intervalToken) {
					clearInterval(this.intervalToken);
					this.intervalToken = null;
				}
				this.activeCount = 0;
			}
		}));

		container.appendChild(element);

		return {
392
			dispose: () => {
J
Joao Moreno 已提交
393
				callOnDispose = dispose(callOnDispose);
394
			}
E
Erich Gamma 已提交
395 396 397 398 399 400 401 402
		};
	}
}

interface TaskServiceEventData {
	error?: any;
}

403
class NullTaskSystem extends EventEmitter implements ITaskSystem {
404
	public run(task: Task): ITaskExecuteResult {
405
		return {
406
			kind: TaskExecuteKind.Started,
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
			promise: TPromise.as<ITaskSummary>({})
		};
	}
	public isActive(): TPromise<boolean> {
		return TPromise.as(false);
	}
	public isActiveSync(): boolean {
		return false;
	}
	public canAutoTerminate(): boolean {
		return true;
	}
	public terminate(): TPromise<TerminateResponse> {
		return TPromise.as<TerminateResponse>({ success: true });
	}
}

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
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();
	}
}

461 462 463 464 465
interface WorkspaceTaskResult {
	taskSet: TaskSet;
	hasErrors: boolean;
}

E
Erich Gamma 已提交
466
class TaskService extends EventEmitter implements ITaskService {
467

468
	// private static autoDetectTelemetryName: string = 'taskServer.autoDetect';
469

470
	public _serviceBrand: any;
E
Erich Gamma 已提交
471
	public static SERVICE_ID: string = 'taskService';
J
Johannes Rieken 已提交
472 473
	public static OutputChannelId: string = 'tasks';
	public static OutputChannelLabel: string = nls.localize('tasks', "Tasks");
E
Erich Gamma 已提交
474 475 476 477 478 479 480 481 482 483 484 485

	private modeService: IModeService;
	private configurationService: IConfigurationService;
	private markerService: IMarkerService;
	private outputService: IOutputService;
	private messageService: IMessageService;
	private fileService: IFileService;
	private telemetryService: ITelemetryService;
	private editorService: IWorkbenchEditorService;
	private contextService: IWorkspaceContextService;
	private textFileService: ITextFileService;
	private modelService: IModelService;
A
Alex Dima 已提交
486
	private extensionService: IExtensionService;
D
Dirk Baeumer 已提交
487
	private quickOpenService: IQuickOpenService;
E
Erich Gamma 已提交
488

489 490 491
	private _configHasErrors: boolean;
	private _workspaceTasksPromise: TPromise<TaskSet>;

E
Erich Gamma 已提交
492
	private _taskSystem: ITaskSystem;
493

A
Alex Dima 已提交
494
	private taskSystemListeners: IDisposable[];
D
Dirk Baeumer 已提交
495
	private clearTaskSystemPromise: boolean;
496
	private outputChannel: IOutputChannel;
E
Erich Gamma 已提交
497

A
Alex Dima 已提交
498
	private fileChangesListener: IDisposable;
499
	private providers: Map<number, ITaskProvider>;
E
Erich Gamma 已提交
500

J
Johannes Rieken 已提交
501
	constructor( @IModeService modeService: IModeService, @IConfigurationService configurationService: IConfigurationService,
E
Erich Gamma 已提交
502
		@IMarkerService markerService: IMarkerService, @IOutputService outputService: IOutputService,
J
Johannes Rieken 已提交
503 504 505
		@IMessageService messageService: IMessageService, @IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService, @IWorkspaceContextService contextService: IWorkspaceContextService,
		@ITelemetryService telemetryService: ITelemetryService, @ITextFileService textFileService: ITextFileService,
506
		@ILifecycleService lifecycleService: ILifecycleService,
A
Alex Dima 已提交
507
		@IModelService modelService: IModelService, @IExtensionService extensionService: IExtensionService,
508
		@IQuickOpenService quickOpenService: IQuickOpenService,
509
		@IEnvironmentService private environmentService: IEnvironmentService,
510 511 512
		@IConfigurationResolverService private configurationResolverService: IConfigurationResolverService,
		@ITerminalService private terminalService: ITerminalService
	) {
E
Erich Gamma 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525

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

529 530
		this._configHasErrors = false;
		this._workspaceTasksPromise = undefined;
E
Erich Gamma 已提交
531
		this.taskSystemListeners = [];
D
Dirk Baeumer 已提交
532
		this.clearTaskSystemPromise = false;
I
isidor 已提交
533
		this.outputChannel = this.outputService.getChannel(TaskService.OutputChannelId);
534
		this.providers = new Map<number, ITaskProvider>();
J
Johannes Rieken 已提交
535
		this.configurationService.onDidUpdateConfiguration(() => {
536
			if (!this._taskSystem) {
537 538
				return;
			}
539 540 541 542 543 544 545 546
			this.updateWorkspaceTasks();
			let currentExecutionEngine = this._taskSystem instanceof TerminalTaskSystem
				? ExecutionEngine.Terminal
				: this._taskSystem instanceof ProcessTaskSystem
					? ExecutionEngine.Process
					: ExecutionEngine.Unknown;
			if (currentExecutionEngine !== this.getExecutionEngine()) {
				this.messageService.show(Severity.Info, nls.localize('TaskSystem.noHotSwap', 'Changing the task execution engine requires to restart VS Code. The change is ignored.'));
D
Dirk Baeumer 已提交
547
			}
E
Erich Gamma 已提交
548
		});
549
		lifecycleService.onWillShutdown(event => event.veto(this.beforeShutdown()));
550 551 552 553
		this.registerCommands();
	}

	private registerCommands(): void {
554
		CommandsRegistry.registerCommand('workbench.action.tasks.runTask', (accessor, arg) => {
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
			this.runTaskCommand(accessor, arg);
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.terminate', (accessor, arg) => {
			this.runTerminateCommand();
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.showLog', () => {
			if (!this.canRunCommand()) {
				return;
			}
			this.showOutput();
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.build', () => {
			if (!this.canRunCommand()) {
				return;
			}
			this.build();
		});

		KeybindingsRegistry.registerKeybindingRule({
			id: 'workbench.action.tasks.build',
			weight: KeybindingsRegistry.WEIGHT.workbenchContrib(),
			when: undefined,
			primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_B
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.test', () => {
			if (!this.canRunCommand()) {
				return;
586
			}
587
			this.runTest();
588
		});
E
Erich Gamma 已提交
589 590
	}

591 592 593 594
	private showOutput(): void {
		this.outputChannel.show(true);
	}

E
Erich Gamma 已提交
595
	private disposeTaskSystemListeners(): void {
A
Alex Dima 已提交
596
		this.taskSystemListeners = dispose(this.taskSystemListeners);
E
Erich Gamma 已提交
597 598
	}

D
Dirk Baeumer 已提交
599
	private disposeFileChangesListener(): void {
E
Erich Gamma 已提交
600
		if (this.fileChangesListener) {
A
Alex Dima 已提交
601
			this.fileChangesListener.dispose();
E
Erich Gamma 已提交
602 603 604 605
			this.fileChangesListener = null;
		}
	}

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
	public registerTaskProvider(handle: number, provider: ITaskProvider): void {
		if (!provider) {
			return;
		}
		this.providers.set(handle, provider);
	}

	public unregisterTaskProvider(handle: number): boolean {
		return this.providers.delete(handle);
	}

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

	public build(): TPromise<ITaskSummary> {
		return this.getTaskSets().then((values) => {
			let runnable = this.createRunnableTask(values, (set) => set.buildTasks);
			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) => {
			let runnable = this.createRunnableTask(values, (set) => set.testTasks);
			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);
676
			} else {
677 678 679 680 681 682 683
				requested = task.name;
				toExecute = resolver.resolve(task._id);
			}
			if (!toExecute) {
				throw new TaskError(Severity.Info, nls.localize('TaskServer.noTask', 'Requested task {0} to execute not found.', requested), TaskErrors.TaskNotFound);
			} else {
				return this.executeTask(toExecute, resolver);
684
			}
685 686 687 688 689 690 691 692 693 694 695 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 727 728 729 730
		}).then(value => value, (error) => {
			this.handleError(error);
			return TPromise.wrapError(error);
		});
	}

	private createRunnableTask(sets: TaskSet[], idFetcher: (set: TaskSet) => string[]): { task: Task; resolver: ITaskResolver } {
		let uuidMap: IStringDictionary<Task> = Object.create(null);
		let identifierMap: IStringDictionary<Task> = Object.create(null);

		let taskIds: string[] = [];
		sets.forEach((set) => {
			set.tasks.forEach((task) => {
				uuidMap[task._id] = task;
				identifierMap[task.identifier] = task;
			});
			let ids: string[] = idFetcher(set);
			if (ids) {
				taskIds.push(...ids);
			}
		});
		if (taskIds.length === 0) {
			return undefined;
		}
		let resolver: ITaskResolver = {
			resolve: (id: string) => {
				let result = uuidMap[id];
				if (result) {
					return result;
				}
				return identifierMap[id];
			}
		};
		if (taskIds.length === 1) {
			return { task: resolver.resolve(taskIds[0]), resolver };
		} else {
			let id: string = UUID.generateUuid();
			let task: Task = {
				_id: id,
				name: id,
				identifier: id,
				dependsOn: taskIds,
				command: undefined,
				showOutput: ShowOutput.Never
			};
			return { task, resolver };
E
Erich Gamma 已提交
731 732 733
		}
	}

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
	private createResolver(sets: TaskSet[]): ITaskResolver {
		let uuidMap: IStringDictionary<Task> = Object.create(null);
		let identifierMap: IStringDictionary<Task> = Object.create(null);

		sets.forEach((set) => {
			set.tasks.forEach((task) => {
				uuidMap[task._id] = task;
				identifierMap[task.identifier] = task;
			});
		});
		return {
			resolve: (id: string) => {
				let result = uuidMap[id];
				if (result) {
					return result;
749
				}
750
				return identifierMap[id];
751
			}
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 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 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
		};
	}

	private executeTask(task: Task, resolver: ITaskResolver): TPromise<ITaskSummary> {
		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 an active running task right now. Terminate it first before executing another task.'), TaskErrors.RunningTask);
				}
			}
			return executeResult.promise;
		});
	}

	public terminate(): TPromise<TerminateResponse> {
		if (!this._taskSystem) {
			return TPromise.as({ success: true });
		}
		return this._taskSystem.terminate().then((response) => {
			this.emit(TaskServiceEvents.Terminated, {});
			this.disposeFileChangesListener();
			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,
				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;
		}
		this.taskSystemListeners.push(this._taskSystem.addListener2(TaskSystemEvents.Active, (event) => this.emit(TaskServiceEvents.Active, event)));
		this.taskSystemListeners.push(this._taskSystem.addListener2(TaskSystemEvents.Inactive, (event) => this.emit(TaskServiceEvents.Inactive, event)));
		return this._taskSystem;
	}

	private getTaskSets(): TPromise<TaskSet[]> {
		return new TPromise<TaskSet[]>((resolve, reject) => {
			let result: TaskSet[] = [];
			let counter: number = 0;
			let done = (value: TaskSet) => {
				result.push(value);
				if (--counter === 0) {
					resolve(result);
				}
			};
			let error = () => {
				if (--counter === 0) {
					resolve(result);
				}
			};
			if (this.getExecutionEngine() === ExecutionEngine.Terminal) {
				this.providers.forEach((provider) => {
					counter++;
					provider.provideTasks().done(done, error);
				});
			}
			// Do this last since the then of a resolved promise returns immediatelly.
			counter++;
			this.getWorkspaceTasks().done(done, error);
		});
	}

	private getWorkspaceTasks(): TPromise<TaskSet> {
		if (this._workspaceTasksPromise) {
			return this._workspaceTasksPromise;
		}
		this._workspaceTasksPromise = this.computeWorkspaceTasks().then(value => {
			this._configHasErrors = value.hasErrors;
			if (this._taskSystem instanceof ProcessTaskSystem) {
				this._taskSystem.hasErrors(this._configHasErrors);
840
			}
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
			return value.taskSet;
		});
		return this._workspaceTasksPromise;
	}

	private updateWorkspaceTasks(): void {
		this._workspaceTasksPromise = this.computeWorkspaceTasks().then(value => {
			this._configHasErrors = value.hasErrors;
			return value.taskSet;
		});
	}

	private computeWorkspaceTasks(): TPromise<WorkspaceTaskResult> {
		let { config, hasParseErrors } = this.getConfiguration();
		if (hasParseErrors) {
			return TPromise.as({ taskSet: undefined, hasErrors: true });
857
		}
858
		let configPromise: TPromise<{ config: TaskConfig.ExternalTaskRunnerConfiguration; hasErrors: boolean }>;
859
		if (config) {
860
			let engine = TaskConfig.ExecutionEngine.from(config);
861
			if (engine === ExecutionEngine.Process && this.hasDetectorSupport(config)) {
862
				configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService, config).detect(true).then((value) => {
863
					let hasErrors = this.printStderr(value.stderr);
864 865 866 867
					let detectedConfig = value.config;
					if (!detectedConfig) {
						return config;
					}
868
					let result: TaskConfig.ExternalTaskRunnerConfiguration = Objects.clone(config);
869
					let configuredTasks: IStringDictionary<TaskConfig.TaskDescription> = Object.create(null);
870 871 872 873 874 875 876 877 878 879 880 881
					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);
							}
						});
					}
882
					return { config: result, hasErrors };
883 884
				});
			} else {
885
				configPromise = TPromise.as({ config, hasErrors: false });
886 887 888
			}
		} else {
			configPromise = new ProcessRunnerDetector(this.fileService, this.contextService, this.configurationResolverService).detect(true).then((value) => {
889 890
				let hasErrors = this.printStderr(value.stderr);
				return { config: value.config, hasErrors };
891 892
			});
		}
893 894 895 896 897 898 899 900 901 902 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
		return configPromise.then((value) => {
			return ProblemMatcherRegistry.onReady().then(() => {
				if (!value || !value.config) {
					return { taskSet: undefined, hasErrors: value !== void 0 ? value.hasErrors : false };
				}
				let problemReporter = new ProblemReporter(this.outputChannel);
				let parseResult = TaskConfig.parse(config, problemReporter);
				let hasErrors = false;
				if (!parseResult.validationStatus.isOK()) {
					hasErrors = true;
					this.showOutput();
				}
				if (problemReporter.status.isFatal()) {
					problemReporter.fatal(nls.localize('TaskSystem.configurationErrors', 'Error: the provided task configuration has validation errors and can\'t not be used. Please correct the errors first.'));
					return { taskSet: undefined, hasErrors };
				}
				return { taskSet: parseResult.taskSet, hasErrors };
			});
		});
	}

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

	private getConfiguration(): { config: TaskConfig.ExternalTaskRunnerConfiguration; hasParseErrors: boolean } {
		let result = this.configurationService.getConfiguration<TaskConfig.ExternalTaskRunnerConfiguration>('tasks');
		if (!result) {
			return undefined;
		}
		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;
				}
935
			}
936 937
			if (isAffected) {
				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'));
938
				this.showOutput();
939
				return { config: undefined, hasParseErrors: true };
940
			}
941 942
		}
		return { config: result, hasParseErrors: false };
943 944
	}

E
Erich Gamma 已提交
945
	private printStderr(stderr: string[]): boolean {
946
		let result = false;
E
Erich Gamma 已提交
947 948
		if (stderr && stderr.length > 0) {
			stderr.forEach((line) => {
949
				result = true;
950
				this.outputChannel.append(line + '\n');
E
Erich Gamma 已提交
951
			});
952
			this.outputChannel.show(true);
E
Erich Gamma 已提交
953 954 955 956
		}
		return result;
	}

957
	public inTerminal(): boolean {
958
		return this._taskSystem instanceof TerminalTaskSystem;
959 960
	}

961
	private hasDetectorSupport(config: TaskConfig.ExternalTaskRunnerConfiguration): boolean {
E
Erich Gamma 已提交
962 963 964 965 966 967
		if (!config.command) {
			return false;
		}
		return ProcessRunnerDetector.supports(config.command);
	}

968 969 970
	public configureAction(): Action {
		return new ConfigureTaskRunnerAction(ConfigureTaskRunnerAction.ID, ConfigureTaskRunnerAction.TEXT,
			this.configurationService, this.editorService, this.fileService, this.contextService,
971
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService);
972 973
	}

974 975 976
	private configureBuildTask(): Action {
		return new ConfigureBuildTaskAction(ConfigureBuildTaskAction.ID, ConfigureBuildTaskAction.TEXT,
			this.configurationService, this.editorService, this.fileService, this.contextService,
977
			this.outputService, this.messageService, this.quickOpenService, this.environmentService, this.configurationResolverService);
978 979
	}

E
Erich Gamma 已提交
980 981
	public beforeShutdown(): boolean | TPromise<boolean> {
		if (this._taskSystem && this._taskSystem.isActiveSync()) {
D
Dirk Baeumer 已提交
982
			if (this._taskSystem.canAutoTerminate() || this.messageService.confirm({
E
Erich Gamma 已提交
983
				message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'),
B
Benjamin Pasero 已提交
984
				primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task")
E
Erich Gamma 已提交
985 986 987 988 989
			})) {
				return this._taskSystem.terminate().then((response) => {
					if (response.success) {
						this.emit(TaskServiceEvents.Terminated, {});
						this._taskSystem = null;
D
Dirk Baeumer 已提交
990
						this.disposeFileChangesListener();
E
Erich Gamma 已提交
991 992
						this.disposeTaskSystemListeners();
						return false; // no veto
D
Dirk Baeumer 已提交
993 994 995 996 997
					} else if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
						return !this.messageService.confirm({
							message: nls.localize('TaskSystem.noProcess', 'The launched task doesn\'t exist anymore. If the task spawned background processes exiting VS Code might result in orphaned processes. To avoid this start the last background process with a wait flag.'),
							primaryButton: nls.localize({ key: 'TaskSystem.exitAnyways', comment: ['&& denotes a mnemonic'] }, "&&Exit Anyways")
						});
E
Erich Gamma 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
					}
					return true; // veto
				}, (err) => {
					return true; // veto
				});
			} else {
				return true; // veto
			}
		}
		return false; // Nothing to do here
	}

1010
	private getConfigureAction(code: TaskErrors): Action {
J
Johannes Rieken 已提交
1011
		switch (code) {
1012 1013 1014 1015 1016 1017
			case TaskErrors.NoBuildTask:
				return this.configureBuildTask();
			default:
				return this.configureAction();
		}
	}
1018

J
Johannes Rieken 已提交
1019
	private handleError(err: any): void {
E
Erich Gamma 已提交
1020 1021 1022
		let showOutput = true;
		if (err instanceof TaskError) {
			let buildError = <TaskError>err;
1023 1024 1025
			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 已提交
1026
				let closeAction = new CloseMessageAction();
1027
				let action: Action = needsConfig
1028
					? this.getConfigureAction(buildError.code)
1029 1030 1031 1032
					: 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 已提交
1033
				closeAction.closeFunction = this.messageService.show(buildError.severity, { message: buildError.message, actions: [action, closeAction] });
E
Erich Gamma 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
			} 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) {
1046
			this.outputChannel.show(true);
E
Erich Gamma 已提交
1047 1048
		}
	}
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064

	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 已提交
1065
					if (task.identifier === arg) {
1066
						this.run(task);
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
					}
				}
			});
		} else {
			this.quickOpenService.show('task ');
		}
	}

	private runTerminateCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
		if (this.inTerminal()) {
			this.messageService.show(Severity.Info, {
				message: nls.localize('TerminateAction.terminalSystem', 'The tasks are executed in the integrated terminal. Use the terminal to manage the tasks.'),
				actions: [new ViewTerminalAction(this.terminalService), new CloseMessageAction()]
			});
		} else {
			this.isActive().then((active) => {
				if (active) {
					this.terminate().then((response) => {
						if (response.success) {
							return undefined;
						} else if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
							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.'));
							return undefined;
						} else {
							return Promise.wrapError(nls.localize('TerminateAction.failed', 'Failed to terminate running task'));
						}
					});
				}
			});
		}
	}
E
Erich Gamma 已提交
1101 1102
}

1103

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

1107 1108 1109 1110 1111
MenuRegistry.addCommand({ id: 'workbench.action.tasks.showLog', title: nls.localize('ShowLogAction.label', "Show Task Log"), alias: 'Tasks: Show Task Log', category: tasksCategory });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.runTask', title: nls.localize('RunTaskAction.label', "Run Task"), alias: 'Tasks: Run Task', category: tasksCategory });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.terminate', title: nls.localize('TerminateAction.label', "Terminate Running Task"), alias: 'Tasks: Terminate Running Task', category: tasksCategory });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.build', title: nls.localize('BuildAction.label', "Run Build Task"), alias: 'Tasks: Run Build Task', category: tasksCategory });
MenuRegistry.addCommand({ id: 'workbench.action.tasks.test', title: nls.localize('TestAction.label', "Run Test Task"), alias: 'Tasks: Run Test Task', category: tasksCategory });
1112 1113
// 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 });
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

// Task Service
registerSingleton(ITaskService, TaskService);

// Register Quick Open
(<IQuickOpenRegistry>Registry.as(QuickOpenExtensions.Quickopen)).registerQuickOpenHandler(
	new QuickOpenHandlerDescriptor(
		'vs/workbench/parts/tasks/browser/taskQuickOpen',
		'QuickOpenHandler',
		'task ',
		nls.localize('taskCommands', "Run Task")
	)
);

// 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 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
let schema: IJSONSchema = {
	id: schemaId,
	description: 'Task definition file',
	type: 'object',
	default: {
		version: '0.1.0',
		command: 'myCommand',
		isShellCommand: false,
		args: [],
		showOutput: 'always',
		tasks: [
1151
			{
D
Dirk Baeumer 已提交
1152 1153 1154 1155
				taskName: 'build',
				showOutput: 'silent',
				isBuildCommand: true,
				problemMatcher: ['$tsc', '$lessCompile']
1156 1157
			}
		]
D
Dirk Baeumer 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
	}
};

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


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