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

import * as nls from 'vs/nls';
import Severity from 'vs/base/common/severity';
import * as Objects from 'vs/base/common/objects';
9
import * as resources from 'vs/base/common/resources';
10
import * as json from 'vs/base/common/json';
11
import { URI } from 'vs/base/common/uri';
E
Erich Gamma 已提交
12 13
import { IStringDictionary } from 'vs/base/common/collections';
import { Action } from 'vs/base/common/actions';
14
import { IDisposable, Disposable, IReference } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
15
import { Event, Emitter } from 'vs/base/common/event';
E
Erich Gamma 已提交
16
import * as Types from 'vs/base/common/types';
17
import { TerminateResponseCode } from 'vs/base/common/processes';
18
import * as strings from 'vs/base/common/strings';
19
import { ValidationStatus, ValidationState } from 'vs/base/common/parsers';
20
import * as UUID from 'vs/base/common/uuid';
21
import * as Platform from 'vs/base/common/platform';
22
import { LRUCache, Touch } from 'vs/base/common/map';
E
Erich Gamma 已提交
23

A
Alex Ross 已提交
24
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
25
import { IMarkerService } from 'vs/platform/markers/common/markers';
E
Erich Gamma 已提交
26
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
27
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
28
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
29
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
30
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
31
import { ProblemMatcherRegistry, NamedProblemMatcher } from 'vs/workbench/contrib/tasks/common/problemMatcher';
B
Benjamin Pasero 已提交
32
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
33
import { IProgressService, IProgressOptions, ProgressLocation } from 'vs/platform/progress/common/progress';
34

35
import { IOpenerService } from 'vs/platform/opener/common/opener';
36
import { IHostService } from 'vs/workbench/services/host/browser/host';
37
import { INotificationService } from 'vs/platform/notification/common/notification';
38
import { IDialogService, IConfirmationResult } from 'vs/platform/dialogs/common/dialogs';
39

E
Erich Gamma 已提交
40 41
import { IModelService } from 'vs/editor/common/services/modelService';

42
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
S
Sandeep Somavarapu 已提交
43
import Constants from 'vs/workbench/contrib/markers/browser/constants';
44
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
45
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
46
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder, IWorkspace } from 'vs/platform/workspace/common/workspace';
E
Erich Gamma 已提交
47

48
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
A
Alex Ross 已提交
49
import { IOutputService, IOutputChannel } from 'vs/workbench/contrib/output/common/output';
E
Erich Gamma 已提交
50

51
import { ITerminalService, ITerminalInstanceService } from 'vs/workbench/contrib/terminal/browser/terminal';
52

53
import { ITaskSystem, ITaskResolver, ITaskSummary, TaskExecuteKind, TaskError, TaskErrors, TaskTerminateResponse, TaskSystemInfo, ITaskExecuteResult } from 'vs/workbench/contrib/tasks/common/taskSystem';
54 55
import {
	Task, CustomTask, ConfiguringTask, ContributedTask, InMemoryTask, TaskEvent,
A
Alex Ross 已提交
56
	TaskSet, TaskGroup, GroupType, ExecutionEngine, JsonSchemaVersion, TaskSourceKind,
57 58
	TaskSorter, TaskIdentifier, KeyedTaskIdentifier, TASK_RUNNING_STATE, TaskRunSource,
	KeyedTaskIdentifier as NKeyedTaskIdentifier, TaskDefinition
59
} from 'vs/workbench/contrib/tasks/common/tasks';
60
import { ITaskService, ITaskProvider, ProblemMatcherRunOptions, CustomizationProperties, TaskFilter, WorkspaceFolderTaskResult, USER_TASKS_GROUP_KEY } from 'vs/workbench/contrib/tasks/common/taskService';
61
import { getTemplates as getTaskTemplates } from 'vs/workbench/contrib/tasks/common/taskTemplates';
E
Erich Gamma 已提交
62

63
import * as TaskConfig from '../common/taskConfiguration';
64
import { TerminalTaskSystem } from './terminalTaskSystem';
65

66
import { IQuickInputService, IQuickPickItem, QuickPickInput, IQuickPick } from 'vs/platform/quickinput/common/quickInput';
67

68
import { TaskDefinitionRegistry } from 'vs/workbench/contrib/tasks/common/taskDefinitionRegistry';
69
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
A
Alex Ross 已提交
70
import { RunAutomaticTasks } from 'vs/workbench/contrib/tasks/browser/runAutomaticTasks';
71

72
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
73
import { IPathService } from 'vs/workbench/services/path/common/pathService';
74
import { format } from 'vs/base/common/jsonFormatter';
75
import { ITextModelService, IResolvedTextEditorModel } from 'vs/editor/common/services/resolverService';
76
import { applyEdits } from 'vs/base/common/jsonEdit';
A
Alex Ross 已提交
77
import { SaveReason } from 'vs/workbench/common/editor';
78
import { ITextEditorSelection, TextEditorSelectionRevealType } from 'vs/platform/editor/common/editor';
79
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
80
import { find } from 'vs/base/common/arrays';
81
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
82
import { IViewsService, IViewDescriptorService } from 'vs/workbench/common/views';
A
Alex Ross 已提交
83
import { isWorkspaceFolder, TaskQuickPickEntry, QUICKOPEN_DETAIL_CONFIG, TaskQuickPick, QUICKOPEN_SKIP_CONFIG } from 'vs/workbench/contrib/tasks/browser/taskQuickPick';
84

85
const QUICKOPEN_HISTORY_LIMIT_CONFIG = 'task.quickOpen.history';
86
const PROBLEM_MATCHER_NEVER_CONFIG = 'task.problemMatchers.neverPrompt';
87
const USE_SLOW_PICKER = 'task.quickOpen.showAll';
88

A
Alex Ross 已提交
89
export namespace ConfigureTaskAction {
90 91
	export const ID = 'workbench.action.tasks.configureTaskRunner';
	export const TEXT = nls.localize('ConfigureTaskRunnerAction.label', "Configure Task");
92 93
}

A
Alex Ross 已提交
94 95
type TaskQuickPickEntryType = (IQuickPickItem & { task: Task; }) | (IQuickPickItem & { folder: IWorkspaceFolder; });

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

A
Alex Ross 已提交
129
export interface WorkspaceFolderConfigurationResult {
S
Sandeep Somavarapu 已提交
130
	workspaceFolder: IWorkspaceFolder;
131
	config: TaskConfig.ExternalTaskRunnerConfiguration | undefined;
132 133 134
	hasErrors: boolean;
}

135
interface TaskCustomizationTelemetryEvent {
136 137 138
	properties: string[];
}

139 140 141 142 143 144 145
class TaskMap {
	private _store: Map<string, Task[]> = new Map();

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

A
Alex Ross 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159
	private getKey(workspaceFolder: IWorkspace | IWorkspaceFolder | string): string {
		let key: string | undefined;
		if (Types.isString(workspaceFolder)) {
			key = workspaceFolder;
		} else {
			const uri: URI | null | undefined = isWorkspaceFolder(workspaceFolder) ? workspaceFolder.uri : workspaceFolder.configuration;
			key = uri ? uri.toString() : '';
		}
		return key;
	}

	public get(workspaceFolder: IWorkspace | IWorkspaceFolder | string): Task[] {
		const key = this.getKey(workspaceFolder);
		let result: Task[] | undefined = this._store.get(key);
160 161
		if (!result) {
			result = [];
A
Alex Ross 已提交
162
			this._store.set(key, result);
163 164 165 166
		}
		return result;
	}

A
Alex Ross 已提交
167 168 169
	public add(workspaceFolder: IWorkspace | IWorkspaceFolder | string, ...task: Task[]): void {
		const key = this.getKey(workspaceFolder);
		let values = this._store.get(key);
170 171
		if (!values) {
			values = [];
A
Alex Ross 已提交
172
			this._store.set(key, values);
173 174 175 176 177 178 179 180 181 182 183
		}
		values.push(...task);
	}

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

184 185 186 187 188 189 190
interface ProblemMatcherDisableMetrics {
	type: string;
}
type ProblemMatcherDisableMetricsClassification = {
	type: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};

A
Alex Ross 已提交
191
export abstract class AbstractTaskService extends Disposable implements ITaskService {
192

193
	// private static autoDetectTelemetryName: string = 'taskServer.autoDetect';
194
	private static readonly RecentlyUsedTasks_Key = 'workbench.tasks.recentlyUsedTasks';
195
	private static readonly RecentlyUsedTasks_KeyV2 = 'workbench.tasks.recentlyUsedTasks2';
196
	private static readonly IgnoreTask010DonotShowAgain_key = 'workbench.tasks.ignoreTask010Shown';
197

198
	private static CustomizationTelemetryEventName: string = 'taskService.customize';
199
	public _serviceBrand: undefined;
J
Johannes Rieken 已提交
200 201
	public static OutputChannelId: string = 'tasks';
	public static OutputChannelLabel: string = nls.localize('tasks', "Tasks");
E
Erich Gamma 已提交
202

203 204
	private static nextHandle: number = 0;

205 206 207
	private _schemaVersion: JsonSchemaVersion | undefined;
	private _executionEngine: ExecutionEngine | undefined;
	private _workspaceFolders: IWorkspaceFolder[] | undefined;
208
	private _workspace: IWorkspace | undefined;
209
	private _ignoredWorkspaceFolders: IWorkspaceFolder[] | undefined;
210
	private _showIgnoreMessage?: boolean;
211
	private _providers: Map<number, ITaskProvider>;
212
	private _providerTypes: Map<number, string>;
A
Alex Ross 已提交
213
	protected _taskSystemInfos: Map<string, TaskSystemInfo>;
214

A
Alex Ross 已提交
215
	protected _workspaceTasksPromise?: Promise<Map<string, WorkspaceFolderTaskResult>>;
A
Alex Ross 已提交
216
	protected _areJsonTasksSupportedPromise: Promise<boolean> = Promise.resolve(false);
217

A
Alex Ross 已提交
218 219
	protected _taskSystem?: ITaskSystem;
	protected _taskSystemListener?: IDisposable;
220
	private _recentlyUsedTasksV1: LRUCache<string, string> | undefined;
221
	private _recentlyUsedTasks: LRUCache<string, string> | undefined;
222

A
Alex Ross 已提交
223
	protected _taskRunningState: IContextKey<boolean>;
D
Dirk Baeumer 已提交
224

A
Alex Ross 已提交
225 226
	protected _outputChannel: IOutputChannel;
	protected readonly _onDidStateChange: Emitter<TaskEvent>;
E
Erich Gamma 已提交
227

D
Dirk Baeumer 已提交
228
	constructor(
229
		@IConfigurationService private readonly configurationService: IConfigurationService,
A
Alex Ross 已提交
230 231
		@IMarkerService protected readonly markerService: IMarkerService,
		@IOutputService protected readonly outputService: IOutputService,
232
		@IPanelService private readonly panelService: IPanelService,
233 234
		@IViewsService private readonly viewsService: IViewsService,
		@ICommandService private readonly commandService: ICommandService,
235
		@IEditorService private readonly editorService: IEditorService,
A
Alex Ross 已提交
236 237 238
		@IFileService protected readonly fileService: IFileService,
		@IWorkspaceContextService protected readonly contextService: IWorkspaceContextService,
		@ITelemetryService protected readonly telemetryService: ITelemetryService,
239
		@ITextFileService private readonly textFileService: ITextFileService,
240
		@ILifecycleService lifecycleService: ILifecycleService,
A
Alex Ross 已提交
241
		@IModelService protected readonly modelService: IModelService,
242 243
		@IExtensionService private readonly extensionService: IExtensionService,
		@IQuickInputService private readonly quickInputService: IQuickInputService,
A
Alex Ross 已提交
244
		@IConfigurationResolverService protected readonly configurationResolverService: IConfigurationResolverService,
245 246
		@ITerminalService private readonly terminalService: ITerminalService,
		@IStorageService private readonly storageService: IStorageService,
247
		@IProgressService private readonly progressService: IProgressService,
248
		@IOpenerService private readonly openerService: IOpenerService,
249
		@IHostService private readonly _hostService: IHostService,
250 251
		@IDialogService private readonly dialogService: IDialogService,
		@INotificationService private readonly notificationService: INotificationService,
D
Dirk Baeumer 已提交
252
		@IContextKeyService contextKeyService: IContextKeyService,
253
		@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
254
		@ITerminalInstanceService private readonly terminalInstanceService: ITerminalInstanceService,
255
		@IPathService private readonly pathService: IPathService,
256
		@ITextModelService private readonly textModelResolverService: ITextModelService,
257 258
		@IPreferencesService private readonly preferencesService: IPreferencesService,
		@IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService
259
	) {
260 261
		super();

262
		this._workspaceTasksPromise = undefined;
263
		this._taskSystem = undefined;
264
		this._taskSystemListener = undefined;
A
Alex Ross 已提交
265
		this._outputChannel = this.outputService.getChannel(AbstractTaskService.OutputChannelId)!;
266
		this._providers = new Map<number, ITaskProvider>();
267
		this._providerTypes = new Map<number, string>();
268
		this._taskSystemInfos = new Map<string, TaskSystemInfo>();
269
		this._register(this.contextService.onDidChangeWorkspaceFolders(() => {
270
			if (!this._taskSystem && !this._workspaceTasksPromise) {
271 272
				return;
			}
D
Dirk Baeumer 已提交
273
			let folderSetup = this.computeWorkspaceFolderSetup();
D
Dirk Baeumer 已提交
274
			if (this.executionEngine !== folderSetup[2]) {
275
				if (this._taskSystem && this._taskSystem.getActiveTasks().length > 0) {
276 277 278 279 280 281 282 283
					this.notificationService.prompt(
						Severity.Info,
						nls.localize(
							'TaskSystem.noHotSwap',
							'Changing the task execution engine with an active task running requires to reload the Window'
						),
						[{
							label: nls.localize('reloadWindow', "Reload Window"),
284
							run: () => this._hostService.reload()
B
Benjamin Pasero 已提交
285 286
						}],
						{ sticky: true }
287
					);
288 289 290 291 292
					return;
				} else {
					this.disposeTaskSystemListeners();
					this._taskSystem = undefined;
				}
D
Dirk Baeumer 已提交
293
			}
D
Dirk Baeumer 已提交
294
			this.updateSetup(folderSetup);
D
Dirk Baeumer 已提交
295
			this.updateWorkspaceTasks();
296
		}));
297
		this._register(this.configurationService.onDidChangeConfiguration(() => {
298 299 300 301 302 303
			if (!this._taskSystem && !this._workspaceTasksPromise) {
				return;
			}
			if (!this._taskSystem || this._taskSystem instanceof TerminalTaskSystem) {
				this._outputChannel.clear();
			}
304 305

			this.setTaskLRUCacheLimit();
306
			this.updateWorkspaceTasks(TaskRunSource.ConfigurationChange);
307
		}));
D
Dirk Baeumer 已提交
308
		this._taskRunningState = TASK_RUNNING_STATE.bindTo(contextKeyService);
309
		this._register(lifecycleService.onBeforeShutdown(event => event.veto(this.beforeShutdown())));
310
		this._onDidStateChange = this._register(new Emitter());
311
		this.registerCommands();
312 313 314 315 316 317 318 319 320 321 322 323 324
		this.configurationResolverService.contributeVariable('defaultBuildTask', async (): Promise<string | undefined> => {
			let tasks = await this.getTasksForGroup(TaskGroup.Build);
			if (tasks.length > 0) {
				let { defaults, users } = this.splitPerGroupType(tasks);
				if (defaults.length === 1) {
					return defaults[0]._label;
				} else if (defaults.length + users.length > 0) {
					tasks = defaults.concat(users);
				}
			}

			let entry: TaskQuickPickEntry | null | undefined;
			if (tasks && tasks.length > 0) {
325
				entry = await this.showQuickPick(tasks, nls.localize('TaskService.pickBuildTaskForLabel', 'Select the build task (there is no default build task defined)'));
326 327 328 329 330 331 332 333
			}

			let task: Task | undefined | null = entry ? entry.task : undefined;
			if (!task) {
				return undefined;
			}
			return task._label;
		});
334 335
	}

336 337 338 339
	public get onDidStateChange(): Event<TaskEvent> {
		return this._onDidStateChange.event;
	}

340 341 342 343
	public get supportsMultipleTaskExecutions(): boolean {
		return this.inTerminal();
	}

344
	private registerCommands(): void {
345 346 347 348 349 350 351 352 353 354 355 356 357 358
		CommandsRegistry.registerCommand({
			id: 'workbench.action.tasks.runTask',
			handler: (accessor, arg) => {
				this.runTaskCommand(arg);
			},
			description: {
				description: 'Run Task',
				args: [{
					name: 'args',
					schema: {
						'type': 'string',
					}
				}]
			}
359 360
		});

A
Alex Ross 已提交
361
		CommandsRegistry.registerCommand('workbench.action.tasks.reRunTask', (accessor, arg) => {
362
			this.reRunTaskCommand();
A
Alex Ross 已提交
363 364
		});

365
		CommandsRegistry.registerCommand('workbench.action.tasks.restartTask', (accessor, arg) => {
366
			this.runRestartTaskCommand(arg);
367 368
		});

369
		CommandsRegistry.registerCommand('workbench.action.tasks.terminate', (accessor, arg) => {
370
			this.runTerminateCommand(arg);
371 372 373 374 375 376 377 378 379 380 381 382 383
		});

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

		CommandsRegistry.registerCommand('workbench.action.tasks.build', () => {
			if (!this.canRunCommand()) {
				return;
			}
384
			this.runBuildCommand();
385 386 387 388 389
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.test', () => {
			if (!this.canRunCommand()) {
				return;
390
			}
391
			this.runTestCommand();
392
		});
393

394 395 396 397
		CommandsRegistry.registerCommand('workbench.action.tasks.configureTaskRunner', () => {
			this.runConfigureTasks();
		});

398 399 400 401 402 403 404
		CommandsRegistry.registerCommand('workbench.action.tasks.configureDefaultBuildTask', () => {
			this.runConfigureDefaultBuildTask();
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.configureDefaultTestTask', () => {
			this.runConfigureDefaultTestTask();
		});
405

406 407
		CommandsRegistry.registerCommand('workbench.action.tasks.showTasks', async () => {
			return this.runShowTasks();
408
		});
409

410
		CommandsRegistry.registerCommand('workbench.action.tasks.toggleProblems', () => this.commandService.executeCommand(Constants.TOGGLE_MARKERS_VIEW_ACTION_ID));
411

412
		CommandsRegistry.registerCommand('workbench.action.tasks.openUserTasks', async () => {
413 414
			const resource = this.getResourceForKind(TaskSourceKind.User);
			if (resource) {
415 416 417 418 419 420 421 422
				this.openTaskFile(resource, TaskSourceKind.User);
			}
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.openWorkspaceFileTasks', async () => {
			const resource = this.getResourceForKind(TaskSourceKind.WorkspaceFile);
			if (resource) {
				this.openTaskFile(resource, TaskSourceKind.WorkspaceFile);
423 424
			}
		});
E
Erich Gamma 已提交
425 426
	}

D
Dirk Baeumer 已提交
427
	private get workspaceFolders(): IWorkspaceFolder[] {
428
		if (!this._workspaceFolders) {
D
Dirk Baeumer 已提交
429 430
			this.updateSetup();
		}
431
		return this._workspaceFolders!;
D
Dirk Baeumer 已提交
432 433
	}

D
Dirk Baeumer 已提交
434
	private get ignoredWorkspaceFolders(): IWorkspaceFolder[] {
435
		if (!this._ignoredWorkspaceFolders) {
D
Dirk Baeumer 已提交
436 437
			this.updateSetup();
		}
438
		return this._ignoredWorkspaceFolders!;
D
Dirk Baeumer 已提交
439 440
	}

A
Alex Ross 已提交
441
	protected get executionEngine(): ExecutionEngine {
R
Rob Lourens 已提交
442
		if (this._executionEngine === undefined) {
D
Dirk Baeumer 已提交
443 444
			this.updateSetup();
		}
445
		return this._executionEngine!;
D
Dirk Baeumer 已提交
446 447 448
	}

	private get schemaVersion(): JsonSchemaVersion {
R
Rob Lourens 已提交
449
		if (this._schemaVersion === undefined) {
D
Dirk Baeumer 已提交
450 451
			this.updateSetup();
		}
452
		return this._schemaVersion!;
D
Dirk Baeumer 已提交
453 454
	}

D
Dirk Baeumer 已提交
455
	private get showIgnoreMessage(): boolean {
R
Rob Lourens 已提交
456
		if (this._showIgnoreMessage === undefined) {
A
Alex Ross 已提交
457
			this._showIgnoreMessage = !this.storageService.getBoolean(AbstractTaskService.IgnoreTask010DonotShowAgain_key, StorageScope.WORKSPACE, false);
D
Dirk Baeumer 已提交
458
		}
459
		return this._showIgnoreMessage;
D
Dirk Baeumer 已提交
460 461
	}

462
	private updateSetup(setup?: [IWorkspaceFolder[], IWorkspaceFolder[], ExecutionEngine, JsonSchemaVersion, IWorkspace | undefined]): void {
D
Dirk Baeumer 已提交
463 464 465
		if (!setup) {
			setup = this.computeWorkspaceFolderSetup();
		}
466 467 468 469
		this._workspaceFolders = setup[0];
		if (this._ignoredWorkspaceFolders) {
			if (this._ignoredWorkspaceFolders.length !== setup[1].length) {
				this._showIgnoreMessage = undefined;
D
Dirk Baeumer 已提交
470 471
			} else {
				let set: Set<string> = new Set();
472
				this._ignoredWorkspaceFolders.forEach(folder => set.add(folder.uri.toString()));
D
Dirk Baeumer 已提交
473 474
				for (let folder of setup[1]) {
					if (!set.has(folder.uri.toString())) {
475
						this._showIgnoreMessage = undefined;
D
Dirk Baeumer 已提交
476 477 478 479 480
						break;
					}
				}
			}
		}
481 482 483
		this._ignoredWorkspaceFolders = setup[1];
		this._executionEngine = setup[2];
		this._schemaVersion = setup[3];
484
		this._workspace = setup[4];
D
Dirk Baeumer 已提交
485 486
	}

A
Alex Ross 已提交
487
	protected showOutput(runSource: TaskRunSource = TaskRunSource.User): void {
A
Alex Ross 已提交
488
		if ((runSource === TaskRunSource.User) || (runSource === TaskRunSource.ConfigurationChange)) {
489 490 491 492 493 494 495
			this.notificationService.prompt(Severity.Warning, nls.localize('taskServiceOutputPrompt', 'There are task errors. See the output for details.'),
				[{
					label: nls.localize('showOutput', "Show output"),
					run: () => {
						this.outputService.showChannel(this._outputChannel.id, true);
					}
				}]);
496
		}
497 498
	}

E
Erich Gamma 已提交
499
	private disposeTaskSystemListeners(): void {
500 501 502
		if (this._taskSystemListener) {
			this._taskSystemListener.dispose();
		}
E
Erich Gamma 已提交
503 504
	}

505
	public registerTaskProvider(provider: ITaskProvider, type: string): IDisposable {
506
		if (!provider) {
507 508 509
			return {
				dispose: () => { }
			};
510
		}
A
Alex Ross 已提交
511
		let handle = AbstractTaskService.nextHandle++;
512
		this._providers.set(handle, provider);
513
		this._providerTypes.set(handle, type);
514 515 516
		return {
			dispose: () => {
				this._providers.delete(handle);
517
				this._providerTypes.delete(handle);
518 519
			}
		};
520 521
	}

522 523 524 525
	public registerTaskSystem(key: string, info: TaskSystemInfo): void {
		this._taskSystemInfos.set(key, info);
	}

G
Gabriel DeBacker 已提交
526
	public extensionCallbackTaskComplete(task: Task, result: number): Promise<void> {
527 528 529
		if (!this._taskSystem) {
			return Promise.resolve();
		}
G
Gabriel DeBacker 已提交
530
		return this._taskSystem.customExecutionComplete(task, result);
531 532
	}

A
Alex Ross 已提交
533 534
	public getTask(folder: IWorkspace | IWorkspaceFolder | string, identifier: string | TaskIdentifier, compareId: boolean = false): Promise<Task | undefined> {
		const name = Types.isString(folder) ? folder : isWorkspaceFolder(folder) ? folder.name : folder.configuration ? resources.basename(folder.configuration) : undefined;
D
Dirk Baeumer 已提交
535
		if (this.ignoredWorkspaceFolders.some(ignored => ignored.name === name)) {
536
			return Promise.reject(new Error(nls.localize('TaskServer.folderIgnored', 'The folder {0} is ignored since it uses task version 0.1.0', name)));
D
Dirk Baeumer 已提交
537
		}
538 539 540 541
		const key: string | KeyedTaskIdentifier | undefined = !Types.isString(identifier)
			? TaskDefinition.createTaskIdentifier(identifier, console)
			: identifier;

R
Rob Lourens 已提交
542
		if (key === undefined) {
543
			return Promise.resolve(undefined);
544
		}
545
		return this.getGroupedTasks().then((map) => {
A
Alex Ross 已提交
546
			let values = map.get(folder);
547
			values = values.concat(map.get(USER_TASKS_GROUP_KEY));
A
Alex Ross 已提交
548

549 550 551
			if (!values) {
				return undefined;
			}
552
			return find(values, task => task.matches(key, compareId));
553 554 555
		});
	}

A
Alex Ross 已提交
556 557 558 559 560 561 562 563
	public async tryResolveTask(configuringTask: ConfiguringTask): Promise<Task | undefined> {
		let matchingProvider: ITaskProvider | undefined;
		for (const [handle, provider] of this._providers) {
			if (configuringTask.type === this._providerTypes.get(handle)) {
				matchingProvider = provider;
				break;
			}
		}
564

A
Alex Ross 已提交
565 566
		if (!matchingProvider) {
			return;
567
		}
A
Alex Ross 已提交
568 569 570 571 572 573

		// Try to resolve the task first
		try {
			const resolvedTask = await matchingProvider.resolveTask(configuringTask);
			if (resolvedTask && (resolvedTask._id === configuringTask._id)) {
				return TaskConfig.createCustomTask(resolvedTask, configuringTask);
574
			}
A
Alex Ross 已提交
575 576 577 578 579 580 581 582 583 584 585 586 587
		} catch (error) {
			// Ignore errors. The task could not be provided by any of the providers.
		}

		// The task couldn't be resolved. Instead, use the less efficient provideTask.
		const tasks = await this.tasks({ type: configuringTask.type });
		for (const task of tasks) {
			if (task._id === configuringTask._id) {
				return TaskConfig.createCustomTask(<ContributedTask>task, configuringTask);
			}
		}

		return;
588 589
	}

A
Alex Ross 已提交
590 591
	protected abstract versionAndEngineCompatible(filter?: TaskFilter): boolean;

A
Alex Ross 已提交
592 593
	public tasks(filter?: TaskFilter): Promise<Task[]> {
		if (!this.versionAndEngineCompatible(filter)) {
594
			return Promise.resolve<Task[]>([]);
595
		}
596
		return this.getGroupedTasks(filter ? filter.type : undefined).then((map) => {
597 598 599 600 601 602
			if (!filter || !filter.type) {
				return map.all();
			}
			let result: Task[] = [];
			map.forEach((tasks) => {
				for (let task of tasks) {
603
					if (ContributedTask.is(task) && ((task.defines.type === filter.type) || (task._source.label === filter.type))) {
604
						result.push(task);
605 606 607 608
					} else if (CustomTask.is(task)) {
						if (task.type === filter.type) {
							result.push(task);
						} else {
A
Alex Ross 已提交
609
							let customizes = task.customizes();
610 611 612 613
							if (customizes && customizes.type === filter.type) {
								result.push(task);
							}
						}
614 615 616 617 618
					}
				}
			});
			return result;
		});
619
	}
620

A
Alex Ross 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633
	public taskTypes(): string[] {
		const types: string[] = [];
		if (this.isProvideTasksEnabled()) {
			for (const [handle] of this._providers) {
				const type = this._providerTypes.get(handle);
				if (type) {
					types.push(type);
				}
			}
		}
		return types;
	}

634 635 636 637
	public createSorter(): TaskSorter {
		return new TaskSorter(this.contextService.getWorkspace() ? this.contextService.getWorkspace().folders : []);
	}

J
Johannes Rieken 已提交
638
	public isActive(): Promise<boolean> {
639
		if (!this._taskSystem) {
640
			return Promise.resolve(false);
641 642 643 644
		}
		return this._taskSystem.isActive();
	}

J
Johannes Rieken 已提交
645
	public getActiveTasks(): Promise<Task[]> {
646
		if (!this._taskSystem) {
647
			return Promise.resolve([]);
648
		}
649
		return Promise.resolve(this._taskSystem.getActiveTasks());
650 651
	}

652 653 654 655 656 657 658
	public getBusyTasks(): Promise<Task[]> {
		if (!this._taskSystem) {
			return Promise.resolve([]);
		}
		return Promise.resolve(this._taskSystem.getBusyTasks());
	}

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
	public getRecentlyUsedTasksV1(): LRUCache<string, string> {
		if (this._recentlyUsedTasksV1) {
			return this._recentlyUsedTasksV1;
		}
		const quickOpenHistoryLimit = this.configurationService.getValue<number>(QUICKOPEN_HISTORY_LIMIT_CONFIG);
		this._recentlyUsedTasksV1 = new LRUCache<string, string>(quickOpenHistoryLimit);

		let storageValue = this.storageService.get(AbstractTaskService.RecentlyUsedTasks_Key, StorageScope.WORKSPACE);
		if (storageValue) {
			try {
				let values: string[] = JSON.parse(storageValue);
				if (Array.isArray(values)) {
					for (let value of values) {
						this._recentlyUsedTasksV1.set(value, value);
					}
				}
			} catch (error) {
				// Ignore. We use the empty result
			}
		}
		return this._recentlyUsedTasksV1;
	}

682
	public getRecentlyUsedTasks(): LRUCache<string, string> {
683 684 685
		if (this._recentlyUsedTasks) {
			return this._recentlyUsedTasks;
		}
686 687 688
		const quickOpenHistoryLimit = this.configurationService.getValue<number>(QUICKOPEN_HISTORY_LIMIT_CONFIG);
		this._recentlyUsedTasks = new LRUCache<string, string>(quickOpenHistoryLimit);

689
		let storageValue = this.storageService.get(AbstractTaskService.RecentlyUsedTasks_KeyV2, StorageScope.WORKSPACE);
690 691
		if (storageValue) {
			try {
692
				let values: [string, string][] = JSON.parse(storageValue);
693 694
				if (Array.isArray(values)) {
					for (let value of values) {
695
						this._recentlyUsedTasks.set(value[0], value[1]);
696 697 698 699 700 701 702 703 704
					}
				}
			} catch (error) {
				// Ignore. We use the empty result
			}
		}
		return this._recentlyUsedTasks;
	}

A
Alex Ross 已提交
705 706 707 708 709 710 711 712 713 714
	private getFolderFromTaskKey(key: string): string | undefined {
		const keyValue: { folder: string | undefined } = JSON.parse(key);
		return keyValue.folder;
	}

	public async readRecentTasks(): Promise<(Task | ConfiguringTask)[]> {
		const folderMap: IStringDictionary<IWorkspaceFolder> = Object.create(null);
		this.workspaceFolders.forEach(folder => {
			folderMap[folder.uri.toString()] = folder;
		});
715
		const folderToTasksMap: Map<string, any> = new Map();
A
Alex Ross 已提交
716 717
		const recentlyUsedTasks = this.getRecentlyUsedTasks();
		const tasks: (Task | ConfiguringTask)[] = [];
718 719
		for (const entry of recentlyUsedTasks.entries()) {
			const key = entry[0];
A
Alex Ross 已提交
720
			const task = JSON.parse(entry[1]);
A
Alex Ross 已提交
721
			const folder = this.getFolderFromTaskKey(key);
722 723 724
			if (folder && !folderToTasksMap.has(folder)) {
				folderToTasksMap.set(folder, []);
			}
A
Alex Ross 已提交
725
			if (folder && (folderMap[folder] || (folder === USER_TASKS_GROUP_KEY)) && task) {
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
				folderToTasksMap.get(folder).push(task);
			}
		}
		const readTasksMap: Map<string, (Task | ConfiguringTask)> = new Map();
		for (const key of folderToTasksMap.keys()) {
			let custom: CustomTask[] = [];
			let customized: IStringDictionary<ConfiguringTask> = Object.create(null);
			await this.computeTasksForSingleConfig(folderMap[key] ?? this.workspaceFolders[0], {
				version: '2.0.0',
				tasks: folderToTasksMap.get(key)
			}, TaskRunSource.System, custom, customized, folderMap[key] ? TaskConfig.TaskConfigSource.TasksJson : TaskConfig.TaskConfigSource.User, true);
			custom.forEach(task => {
				const taskKey = task.getRecentlyUsedKey();
				if (taskKey) {
					readTasksMap.set(taskKey, task);
A
Alex Ross 已提交
741
				}
742 743 744 745 746 747 748 749
			});
			for (const configuration in customized) {
				const taskKey = customized[configuration].getRecentlyUsedKey();
				if (taskKey) {
					readTasksMap.set(taskKey, customized[configuration]);
				}
			}
		}
A
Alex Ross 已提交
750

751 752 753
		for (const key of recentlyUsedTasks.keys()) {
			if (readTasksMap.has(key)) {
				tasks.push(readTasksMap.get(key)!);
A
Alex Ross 已提交
754 755 756 757 758
			}
		}
		return tasks;
	}

759 760 761 762 763 764 765
	private setTaskLRUCacheLimit() {
		const quickOpenHistoryLimit = this.configurationService.getValue<number>(QUICKOPEN_HISTORY_LIMIT_CONFIG);
		if (this._recentlyUsedTasks) {
			this._recentlyUsedTasks.limit = quickOpenHistoryLimit;
		}
	}

766 767
	private async setRecentlyUsedTask(task: Task): Promise<void> {
		let key = task.getRecentlyUsedKey();
768
		if (!InMemoryTask.is(task) && key) {
769 770 771 772 773 774 775 776 777 778 779 780 781
			const customizations = this.createCustomizableTask(task);
			if (ContributedTask.is(task) && customizations) {
				let custom: CustomTask[] = [];
				let customized: IStringDictionary<ConfiguringTask> = Object.create(null);
				await this.computeTasksForSingleConfig(task._source.workspaceFolder ?? this.workspaceFolders[0], {
					version: '2.0.0',
					tasks: [customizations]
				}, TaskRunSource.System, custom, customized, TaskConfig.TaskConfigSource.TasksJson, true);
				for (const configuration in customized) {
					key = customized[configuration].getRecentlyUsedKey()!;
				}
			}
			this.getRecentlyUsedTasks().set(key, JSON.stringify(customizations));
782 783
			this.saveRecentlyUsedTasks();
		}
784 785 786
	}

	private saveRecentlyUsedTasks(): void {
787
		if (!this._recentlyUsedTasks) {
788 789
			return;
		}
790 791 792 793 794
		const quickOpenHistoryLimit = this.configurationService.getValue<number>(QUICKOPEN_HISTORY_LIMIT_CONFIG);
		// setting history limit to 0 means no LRU sorting
		if (quickOpenHistoryLimit === 0) {
			return;
		}
795
		let keys = [...this._recentlyUsedTasks.keys()];
A
Alex Ross 已提交
796 797 798 799 800
		if (keys.length > quickOpenHistoryLimit) {
			keys = keys.slice(0, quickOpenHistoryLimit);
		}
		const keyValues: [string, string][] = [];
		for (const key of keys) {
801
			keyValues.push([key, this._recentlyUsedTasks.get(key, Touch.None)!]);
802
		}
A
Alex Ross 已提交
803
		this.storageService.store(AbstractTaskService.RecentlyUsedTasks_KeyV2, JSON.stringify(keyValues), StorageScope.WORKSPACE);
804
	}
805

806
	private openDocumentation(): void {
807 808 809
		this.openerService.open(URI.parse('https://go.microsoft.com/fwlink/?LinkId=733558'));
	}

J
Johannes Rieken 已提交
810
	public build(): Promise<ITaskSummary> {
811
		return this.getGroupedTasks().then((tasks) => {
D
Dirk Baeumer 已提交
812
			let runnable = this.createRunnableTask(tasks, TaskGroup.Build);
813
			if (!runnable || !runnable.task) {
D
Dirk Baeumer 已提交
814
				if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
815 816 817 818
					throw new TaskError(Severity.Info, nls.localize('TaskService.noBuildTask1', 'No build task defined. Mark a task with \'isBuildCommand\' in the tasks.json file.'), TaskErrors.NoBuildTask);
				} else {
					throw new TaskError(Severity.Info, nls.localize('TaskService.noBuildTask2', 'No build task defined. Mark a task with as a \'build\' group in the tasks.json file.'), TaskErrors.NoBuildTask);
				}
819 820 821 822
			}
			return this.executeTask(runnable.task, runnable.resolver);
		}).then(value => value, (error) => {
			this.handleError(error);
823
			return Promise.reject(error);
824 825 826
		});
	}

J
Johannes Rieken 已提交
827
	public runTest(): Promise<ITaskSummary> {
828
		return this.getGroupedTasks().then((tasks) => {
D
Dirk Baeumer 已提交
829
			let runnable = this.createRunnableTask(tasks, TaskGroup.Test);
830
			if (!runnable || !runnable.task) {
D
Dirk Baeumer 已提交
831
				if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
832 833 834 835
					throw new TaskError(Severity.Info, nls.localize('TaskService.noTestTask1', 'No test task defined. Mark a task with \'isTestCommand\' in the tasks.json file.'), TaskErrors.NoTestTask);
				} else {
					throw new TaskError(Severity.Info, nls.localize('TaskService.noTestTask2', 'No test task defined. Mark a task with as a \'test\' group in the tasks.json file.'), TaskErrors.NoTestTask);
				}
836 837 838 839
			}
			return this.executeTask(runnable.task, runnable.resolver);
		}).then(value => value, (error) => {
			this.handleError(error);
840
			return Promise.reject(error);
841 842 843
		});
	}

A
Alex Ross 已提交
844
	public run(task: Task | undefined, options?: ProblemMatcherRunOptions, runSource: TaskRunSource = TaskRunSource.System): Promise<ITaskSummary | undefined> {
845 846 847
		if (!task) {
			throw new TaskError(Severity.Info, nls.localize('TaskServer.noTask', 'Task to execute is undefined'), TaskErrors.TaskNotFound);
		}
A
Alex Ross 已提交
848 849 850

		return new Promise<ITaskSummary | undefined>(async (resolve) => {
			let resolver = this.createResolver();
851
			if (options && options.attachProblemMatcher && this.shouldAttachProblemMatcher(task) && !InMemoryTask.is(task)) {
A
Alex Ross 已提交
852 853 854 855 856 857
				const toExecute = await this.attachProblemMatcher(task);
				if (toExecute) {
					resolve(this.executeTask(toExecute, resolver));
				} else {
					resolve(undefined);
				}
A
Alex Ross 已提交
858 859
			} else {
				resolve(this.executeTask(task, resolver));
860
			}
861 862 863 864 865 866 867 868
		}).then((value) => {
			if (runSource === TaskRunSource.User) {
				this.getWorkspaceTasks().then(workspaceTasks => {
					RunAutomaticTasks.promptForPermission(this, this.storageService, this.notificationService, workspaceTasks);
				});
			}
			return value;
		}, (error) => {
869
			this.handleError(error);
870
			return Promise.reject(error);
871 872 873
		});
	}

874 875
	private isProvideTasksEnabled(): boolean {
		const settingValue = this.configurationService.getValue('task.autoDetect');
876
		return settingValue === 'on';
877 878
	}

879
	private isProblemMatcherPromptEnabled(type?: string): boolean {
880
		const settingValue = this.configurationService.getValue(PROBLEM_MATCHER_NEVER_CONFIG);
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
		if (Types.isBoolean(settingValue)) {
			return !settingValue;
		}
		if (type === undefined) {
			return true;
		}
		const settingValueMap: IStringDictionary<boolean> = <any>settingValue;
		return !settingValueMap[type];
	}

	private getTypeForTask(task: Task): string {
		let type: string;
		if (CustomTask.is(task)) {
			let configProperties: TaskConfig.ConfigurationProperties = task._source.config.element;
			type = (<any>configProperties).type;
		} else {
			type = task.getDefinition()!.type;
		}
		return type;
	}

	private shouldAttachProblemMatcher(task: Task): boolean {
		const enabled = this.isProblemMatcherPromptEnabled(this.getTypeForTask(task));
		if (enabled === false) {
905 906
			return false;
		}
D
Dirk Baeumer 已提交
907
		if (!this.canCustomize(task)) {
908 909
			return false;
		}
R
Rob Lourens 已提交
910
		if (task.configurationProperties.group !== undefined && task.configurationProperties.group !== TaskGroup.Build) {
911 912
			return false;
		}
R
Rob Lourens 已提交
913
		if (task.configurationProperties.problemMatchers !== undefined && task.configurationProperties.problemMatchers.length > 0) {
914 915
			return false;
		}
916
		if (ContributedTask.is(task)) {
917
			return !task.hasDefinedMatchers && !!task.configurationProperties.problemMatchers && (task.configurationProperties.problemMatchers.length === 0);
918
		}
919 920
		if (CustomTask.is(task)) {
			let configProperties: TaskConfig.ConfigurationProperties = task._source.config.element;
921
			return configProperties.problemMatcher === undefined && !task.hasDefinedMatchers;
922 923
		}
		return false;
924 925
	}

926 927 928 929 930 931
	private async updateNeverProblemMatcherSetting(type: string): Promise<void> {
		this.telemetryService.publicLog2<ProblemMatcherDisableMetrics, ProblemMatcherDisableMetricsClassification>('problemMatcherDisabled', { type });
		const current = this.configurationService.getValue(PROBLEM_MATCHER_NEVER_CONFIG);
		if (current === true) {
			return;
		}
932 933 934 935 936
		let newValue: IStringDictionary<boolean>;
		if (current !== false) {
			newValue = <any>current;
		} else {
			newValue = Object.create(null);
937
		}
938 939
		newValue[type] = true;
		return this.configurationService.updateValue(PROBLEM_MATCHER_NEVER_CONFIG, newValue, ConfigurationTarget.USER);
940 941
	}

942
	private attachProblemMatcher(task: ContributedTask | CustomTask): Promise<Task | undefined> {
C
Christof Marti 已提交
943
		interface ProblemMatcherPickEntry extends IQuickPickItem {
944
			matcher: NamedProblemMatcher | undefined;
945
			never?: boolean;
946
			learnMore?: boolean;
947
			setting?: string;
948
		}
C
Christof Marti 已提交
949
		let entries: QuickPickInput<ProblemMatcherPickEntry>[] = [];
950 951
		for (let key of ProblemMatcherRegistry.keys()) {
			let matcher = ProblemMatcherRegistry.get(key);
952 953 954
			if (matcher.deprecated) {
				continue;
			}
955 956 957 958 959 960 961 962 963 964 965
			if (matcher.name === matcher.label) {
				entries.push({ label: matcher.name, matcher: matcher });
			} else {
				entries.push({
					label: matcher.label,
					description: `$${matcher.name}`,
					matcher: matcher
				});
			}
		}
		if (entries.length > 0) {
966 967 968 969 970 971 972
			entries = entries.sort((a, b) => {
				if (a.label && b.label) {
					return a.label.localeCompare(b.label);
				} else {
					return 0;
				}
			});
C
Christof Marti 已提交
973
			entries.unshift({ type: 'separator', label: nls.localize('TaskService.associate', 'associate') });
974 975 976 977 978 979 980
			let taskType: string;
			if (CustomTask.is(task)) {
				let configProperties: TaskConfig.ConfigurationProperties = task._source.config.element;
				taskType = (<any>configProperties).type;
			} else {
				taskType = task.getDefinition().type;
			}
981
			entries.unshift(
982
				{ label: nls.localize('TaskService.attachProblemMatcher.continueWithout', 'Continue without scanning the task output'), matcher: undefined },
983 984
				{ label: nls.localize('TaskService.attachProblemMatcher.never', 'Never scan the task output for this task'), matcher: undefined, never: true },
				{ label: nls.localize('TaskService.attachProblemMatcher.neverType', 'Never scan the task output for {0} tasks', taskType), matcher: undefined, setting: taskType },
985
				{ label: nls.localize('TaskService.attachProblemMatcher.learnMoreAbout', 'Learn more about scanning the task output'), matcher: undefined, learnMore: true }
986
			);
C
Christof Marti 已提交
987
			return this.quickInputService.pick(entries, {
988
				placeHolder: nls.localize('selectProblemMatcher', 'Select for which kind of errors and warnings to scan the task output'),
989
			}).then(async (selected) => {
990 991 992 993
				if (selected) {
					if (selected.learnMore) {
						this.openDocumentation();
						return undefined;
994 995 996
					} else if (selected.never) {
						this.customize(task, { problemMatcher: [] }, true);
						return task;
997
					} else if (selected.matcher) {
A
Alex Ross 已提交
998
						let newTask = task.clone();
999
						let matcherReference = `$${selected.matcher.name}`;
1000
						let properties: CustomizationProperties = { problemMatcher: [matcherReference] };
A
Alex Ross 已提交
1001
						newTask.configurationProperties.problemMatchers = [matcherReference];
1002
						let matcher = ProblemMatcherRegistry.get(selected.matcher.name);
R
Rob Lourens 已提交
1003
						if (matcher && matcher.watching !== undefined) {
1004
							properties.isBackground = true;
A
Alex Ross 已提交
1005
							newTask.configurationProperties.isBackground = true;
1006 1007
						}
						this.customize(task, properties, true);
1008
						return newTask;
1009 1010 1011
					} else if (selected.setting) {
						await this.updateNeverProblemMatcherSetting(selected.setting);
						return task;
1012 1013 1014 1015
					} else {
						return task;
					}
				} else {
1016
					return undefined;
1017 1018 1019
				}
			});
		}
1020
		return Promise.resolve(task);
1021 1022
	}

J
Johannes Rieken 已提交
1023
	public getTasksForGroup(group: string): Promise<Task[]> {
1024
		return this.getGroupedTasks().then((groups) => {
1025
			let result: Task[] = [];
1026 1027
			groups.forEach((tasks) => {
				for (let task of tasks) {
A
Alex Ross 已提交
1028
					if (task.configurationProperties.group === group) {
1029 1030
						result.push(task);
					}
1031
				}
1032
			});
1033 1034 1035 1036
			return result;
		});
	}

1037 1038
	public needsFolderQualification(): boolean {
		return this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE;
D
Dirk Baeumer 已提交
1039 1040 1041
	}

	public canCustomize(task: Task): boolean {
D
Dirk Baeumer 已提交
1042
		if (this.schemaVersion !== JsonSchemaVersion.V2_0_0) {
D
Dirk Baeumer 已提交
1043 1044 1045 1046 1047 1048
			return false;
		}
		if (CustomTask.is(task)) {
			return true;
		}
		if (ContributedTask.is(task)) {
A
Alex Ross 已提交
1049
			return !!task.getWorkspaceFolder();
D
Dirk Baeumer 已提交
1050 1051
		}
		return false;
1052 1053
	}

A
Alex Ross 已提交
1054
	private openEditorAtTask(resource: URI | undefined, task: TaskConfig.CustomTask | TaskConfig.ConfiguringTask | string | undefined): Promise<boolean> {
1055
		if (resource === undefined) {
A
Alex Ross 已提交
1056
			return Promise.resolve(false);
1057 1058 1059 1060
		}
		let selection: ITextEditorSelection | undefined;
		return this.fileService.readFile(resource).then(content => content.value).then(async content => {
			if (!content) {
A
Alex Ross 已提交
1061
				return false;
1062 1063 1064 1065 1066 1067 1068
			}
			if (task) {
				const contentValue = content.toString();
				let stringValue: string;
				if (typeof task === 'string') {
					stringValue = task;
				} else {
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
					let reference: IReference<IResolvedTextEditorModel> | undefined;
					try {
						reference = await this.textModelResolverService.createModelReference(resource);
						const model = reference.object.textEditorModel;
						const { tabSize, insertSpaces } = model.getOptions();
						const eol = model.getEOL();
						const edits = format(JSON.stringify(task), undefined, { eol, tabSize, insertSpaces });
						let stringified = applyEdits(JSON.stringify(task), edits);
						const regex = new RegExp(eol + '\\t', 'g');
						stringified = stringified.replace(regex, eol + '\t\t\t');
						const twoTabs = '\t\t';
						stringValue = twoTabs + stringified.slice(0, stringified.length - 1) + twoTabs + stringified.slice(stringified.length - 1);
					} finally {
						if (reference) {
							reference.dispose();
						}
					}
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
				}

				const index = contentValue.indexOf(stringValue);
				let startLineNumber = 1;
				for (let i = 0; i < index; i++) {
					if (contentValue.charAt(i) === '\n') {
						startLineNumber++;
					}
				}
				let endLineNumber = startLineNumber;
				for (let i = 0; i < stringValue.length; i++) {
					if (stringValue.charAt(i) === '\n') {
						endLineNumber++;
					}
				}
				selection = startLineNumber > 1 ? { startLineNumber, startColumn: startLineNumber === endLineNumber ? 4 : 3, endLineNumber, endColumn: startLineNumber === endLineNumber ? undefined : 4 } : undefined;
			}

			return this.editorService.openEditor({
				resource,
				options: {
					pinned: false,
					forceReload: true, // because content might have changed
					selection,
1110
					selectionRevealType: TextEditorSelectionRevealType.CenterIfOutsideViewport
1111
				}
A
Alex Ross 已提交
1112
			}).then(() => !!selection);
1113 1114 1115
		});
	}

A
Alex Ross 已提交
1116
	private createCustomizableTask(task: ContributedTask | CustomTask | ConfiguringTask): TaskConfig.CustomTask | TaskConfig.ConfiguringTask | undefined {
1117
		let toCustomize: TaskConfig.CustomTask | TaskConfig.ConfiguringTask | undefined;
A
Alex Ross 已提交
1118
		let taskConfig = CustomTask.is(task) || ConfiguringTask.is(task) ? task._source.config : undefined;
1119
		if (taskConfig && taskConfig.element) {
1120
			toCustomize = { ...(taskConfig.element) };
1121 1122 1123 1124 1125
		} else if (ContributedTask.is(task)) {
			toCustomize = {
			};
			let identifier: TaskConfig.TaskIdentifier = Objects.assign(Object.create(null), task.defines);
			delete identifier['_key'];
1126
			Object.keys(identifier).forEach(key => (<any>toCustomize)![key] = identifier[key]);
A
Alex Ross 已提交
1127 1128
			if (task.configurationProperties.problemMatchers && task.configurationProperties.problemMatchers.length > 0 && Types.isStringArray(task.configurationProperties.problemMatchers)) {
				toCustomize.problemMatcher = task.configurationProperties.problemMatchers;
1129
			}
A
Alex Ross 已提交
1130 1131 1132
			if (task.configurationProperties.group) {
				toCustomize.group = task.configurationProperties.group;
			}
1133 1134
		}
		if (!toCustomize) {
1135 1136 1137 1138 1139
			return undefined;
		}
		if (toCustomize.problemMatcher === undefined && task.configurationProperties.problemMatchers === undefined || (task.configurationProperties.problemMatchers && task.configurationProperties.problemMatchers.length === 0)) {
			toCustomize.problemMatcher = [];
		}
A
Alex Ross 已提交
1140 1141 1142 1143 1144 1145
		if (task._source.label !== 'Workspace') {
			toCustomize.label = task.configurationProperties.identifier;
		} else {
			toCustomize.label = task._label;
		}
		toCustomize.detail = task.configurationProperties.detail;
1146 1147 1148
		return toCustomize;
	}

A
Alex Ross 已提交
1149
	public customize(task: ContributedTask | CustomTask | ConfiguringTask, properties?: CustomizationProperties, openConfig?: boolean): Promise<void> {
1150 1151
		const workspaceFolder = task.getWorkspaceFolder();
		if (!workspaceFolder) {
1152
			return Promise.resolve(undefined);
1153
		}
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
		let configuration = this.getConfiguration(workspaceFolder, task._source.kind);
		if (configuration.hasParseErrors) {
			this.notificationService.warn(nls.localize('customizeParseErrors', 'The current task configuration has errors. Please fix the errors first before customizing a task.'));
			return Promise.resolve<void>(undefined);
		}

		let fileConfig = configuration.config;
		const toCustomize = this.createCustomizableTask(task);
		if (!toCustomize) {
			return Promise.resolve(undefined);
		}
		const index: number | undefined = CustomTask.is(task) ? task._source.config.index : undefined;
1166 1167
		if (properties) {
			for (let property of Object.getOwnPropertyNames(properties)) {
1168
				let value = (<any>properties)[property];
R
Rob Lourens 已提交
1169
				if (value !== undefined && value !== null) {
1170
					(<any>toCustomize)[property] = value;
1171 1172
				}
			}
1173
		}
1174

1175
		let promise: Promise<void> | undefined;
D
Dirk Baeumer 已提交
1176
		if (!fileConfig) {
1177
			let value = {
D
Dirk Baeumer 已提交
1178
				version: '2.0.0',
1179
				tasks: [toCustomize]
D
Dirk Baeumer 已提交
1180
			};
1181 1182
			let content = [
				'{',
1183
				nls.localize('tasksJsonComment', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558 \n\t// for the documentation about the tasks.json format'),
1184
			].join('\n') + JSON.stringify(value, null, '\t').substr(1);
1185
			let editorConfig = this.configurationService.getValue<any>();
1186 1187 1188
			if (editorConfig.editor.insertSpaces) {
				content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + strings.repeat(' ', s2.length * editorConfig.editor.tabSize));
			}
1189
			promise = this.textFileService.create(workspaceFolder.toResource('.vscode/tasks.json'), content).then(() => { });
D
Dirk Baeumer 已提交
1190
		} else {
1191
			// We have a global task configuration
1192
			if ((index === -1) && properties) {
R
Rob Lourens 已提交
1193
				if (properties.problemMatcher !== undefined) {
1194
					fileConfig.problemMatcher = properties.problemMatcher;
1195
					promise = this.writeConfiguration(workspaceFolder, 'tasks.problemMatchers', fileConfig.problemMatcher, task._source.kind);
R
Rob Lourens 已提交
1196
				} else if (properties.group !== undefined) {
1197
					fileConfig.group = properties.group;
1198
					promise = this.writeConfiguration(workspaceFolder, 'tasks.group', fileConfig.group, task._source.kind);
1199
				}
1200 1201 1202 1203
			} else {
				if (!Array.isArray(fileConfig.tasks)) {
					fileConfig.tasks = [];
				}
R
Rob Lourens 已提交
1204
				if (index === undefined) {
1205 1206 1207 1208
					fileConfig.tasks.push(toCustomize);
				} else {
					fileConfig.tasks[index] = toCustomize;
				}
1209
				promise = this.writeConfiguration(workspaceFolder, 'tasks.tasks', fileConfig.tasks, task._source.kind);
D
Dirk Baeumer 已提交
1210
			}
1211
		}
1212
		if (!promise) {
1213
			return Promise.resolve(undefined);
1214
		}
1215
		return promise.then(() => {
1216
			let event: TaskCustomizationTelemetryEvent = {
1217 1218
				properties: properties ? Object.getOwnPropertyNames(properties) : []
			};
K
kieferrm 已提交
1219
			/* __GDPR__
K
kieferrm 已提交
1220 1221 1222 1223
				"taskService.customize" : {
					"properties" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
A
Alex Ross 已提交
1224
			this.telemetryService.publicLog(AbstractTaskService.CustomizationTelemetryEventName, event);
D
Dirk Baeumer 已提交
1225
			if (openConfig) {
1226
				this.openEditorAtTask(this.getResourceForTask(task), toCustomize);
D
Dirk Baeumer 已提交
1227 1228 1229 1230
			}
		});
	}

1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
	private writeConfiguration(workspaceFolder: IWorkspaceFolder, key: string, value: any, source?: string): Promise<void> | undefined {
		let target: ConfigurationTarget | undefined = undefined;
		switch (source) {
			case TaskSourceKind.User: target = ConfigurationTarget.USER; break;
			case TaskSourceKind.WorkspaceFile: target = ConfigurationTarget.WORKSPACE; break;
			default: if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
				target = ConfigurationTarget.WORKSPACE;
			} else if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
				target = ConfigurationTarget.WORKSPACE_FOLDER;
			}
		}
		if (target) {
			return this.configurationService.updateValue(key, value, { resource: workspaceFolder.uri }, target);
D
Dirk Baeumer 已提交
1244 1245 1246 1247 1248
		} else {
			return undefined;
		}
	}

1249
	private getResourceForKind(kind: string): URI | undefined {
1250
		this.updateSetup();
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
		switch (kind) {
			case TaskSourceKind.User: {
				return resources.joinPath(resources.dirname(this.preferencesService.userSettingsResource), 'tasks.json');
			}
			case TaskSourceKind.WorkspaceFile: {
				if (this._workspace && this._workspace.configuration) {
					return this._workspace.configuration;
				}
			}
			default: {
				return undefined;
			}
		}
	}

1266
	private getResourceForTask(task: CustomTask | ConfiguringTask | ContributedTask): URI {
1267 1268 1269 1270 1271 1272 1273 1274 1275
		if (CustomTask.is(task)) {
			let uri = this.getResourceForKind(task._source.kind);
			if (!uri) {
				const taskFolder = task.getWorkspaceFolder();
				if (taskFolder) {
					uri = taskFolder.toResource(task._source.config.file);
				} else {
					uri = this.workspaceFolders[0].uri;
				}
A
Alex Ross 已提交
1276
			}
1277 1278 1279
			return uri;
		} else {
			return task.getWorkspaceFolder()!.toResource('.vscode/tasks.json');
1280 1281 1282
		}
	}

A
Alex Ross 已提交
1283
	public openConfig(task: CustomTask | ConfiguringTask | undefined): Promise<boolean> {
1284
		let resource: URI | undefined;
1285
		if (task) {
1286
			resource = this.getResourceForTask(task);
1287 1288 1289
		} else {
			resource = (this._workspaceFolders && (this._workspaceFolders.length > 0)) ? this._workspaceFolders[0].toResource('.vscode/tasks.json') : undefined;
		}
A
Alex Ross 已提交
1290
		return this.openEditorAtTask(resource, task ? task._label : undefined);
1291 1292
	}

1293
	private createRunnableTask(tasks: TaskMap, group: TaskGroup): { task: Task; resolver: ITaskResolver } | undefined {
1294 1295 1296 1297 1298
		interface ResolverData {
			id: Map<string, Task>;
			label: Map<string, Task>;
			identifier: Map<string, Task>;
		}
1299

1300
		let resolverData: Map<string, ResolverData> = new Map();
1301 1302
		let workspaceTasks: Task[] = [];
		let extensionTasks: Task[] = [];
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
		tasks.forEach((tasks, folder) => {
			let data = resolverData.get(folder);
			if (!data) {
				data = {
					id: new Map<string, Task>(),
					label: new Map<string, Task>(),
					identifier: new Map<string, Task>()
				};
				resolverData.set(folder, data);
			}
			for (let task of tasks) {
				data.id.set(task._id, task);
				data.label.set(task._label, task);
1316 1317 1318
				if (task.configurationProperties.identifier) {
					data.identifier.set(task.configurationProperties.identifier, task);
				}
A
Alex Ross 已提交
1319
				if (group && task.configurationProperties.group === group) {
1320 1321 1322 1323 1324
					if (task._source.kind === TaskSourceKind.Workspace) {
						workspaceTasks.push(task);
					} else {
						extensionTasks.push(task);
					}
1325
				}
D
Dirk Baeumer 已提交
1326
			}
1327 1328
		});
		let resolver: ITaskResolver = {
A
Alex Ross 已提交
1329
			resolve: async (uri: URI | string, alias: string) => {
1330
				let data = resolverData.get(typeof uri === 'string' ? uri : uri.toString());
1331 1332 1333 1334
				if (!data) {
					return undefined;
				}
				return data.id.get(alias) || data.label.get(alias) || data.identifier.get(alias);
1335 1336
			}
		};
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
		if (workspaceTasks.length > 0) {
			if (workspaceTasks.length > 1) {
				this._outputChannel.append(nls.localize('moreThanOneBuildTask', 'There are many build tasks defined in the tasks.json. Executing the first one.\n'));
			}
			return { task: workspaceTasks[0], resolver };
		}
		if (extensionTasks.length === 0) {
			return undefined;
		}

1347 1348
		// We can only have extension tasks if we are in version 2.0.0. Then we can even run
		// multiple build tasks.
1349 1350
		if (extensionTasks.length === 1) {
			return { task: extensionTasks[0], resolver };
1351 1352
		} else {
			let id: string = UUID.generateUuid();
A
Alex Ross 已提交
1353 1354 1355 1356 1357 1358 1359 1360
			let task: InMemoryTask = new InMemoryTask(
				id,
				{ kind: TaskSourceKind.InMemory, label: 'inMemory' },
				id,
				'inMemory',
				{ reevaluateOnRerun: true },
				{
					identifier: id,
1361
					dependsOn: extensionTasks.map((extensionTask) => { return { uri: extensionTask.getWorkspaceFolder()!.uri, task: extensionTask._id }; }),
A
Alex Ross 已提交
1362 1363 1364
					name: id,
				}
			);
1365
			return { task, resolver };
E
Erich Gamma 已提交
1366 1367 1368
		}
	}

A
Alex Ross 已提交
1369
	private createResolver(grouped?: TaskMap): ITaskResolver {
1370 1371 1372
		interface ResolverData {
			label: Map<string, Task>;
			identifier: Map<string, Task>;
1373
			taskIdentifier: Map<string, Task>;
1374
		}
1375

A
Alex Ross 已提交
1376
		let resolverData: Map<string, ResolverData> | undefined;
1377

1378
		return {
A
Alex Ross 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
			resolve: async (uri: URI | string, identifier: string | TaskIdentifier | undefined) => {
				if (resolverData === undefined) {
					resolverData = new Map();
					(grouped || await this.getGroupedTasks()).forEach((tasks, folder) => {
						let data = resolverData!.get(folder);
						if (!data) {
							data = { label: new Map<string, Task>(), identifier: new Map<string, Task>(), taskIdentifier: new Map<string, Task>() };
							resolverData!.set(folder, data);
						}
						for (let task of tasks) {
							data.label.set(task._label, task);
							if (task.configurationProperties.identifier) {
								data.identifier.set(task.configurationProperties.identifier, task);
							}
							let keyedIdentifier = task.getDefinition(true);
							if (keyedIdentifier !== undefined) {
								data.taskIdentifier.set(keyedIdentifier._key, task);
							}
						}
					});
				}
1400
				let data = resolverData.get(typeof uri === 'string' ? uri : uri.toString());
1401
				if (!data || !identifier) {
1402 1403
					return undefined;
				}
1404 1405 1406 1407
				if (Types.isString(identifier)) {
					return data.label.get(identifier) || data.identifier.get(identifier);
				} else {
					let key = TaskDefinition.createTaskIdentifier(identifier, console);
R
Rob Lourens 已提交
1408
					return key !== undefined ? data.taskIdentifier.get(key._key) : undefined;
1409
				}
1410
			}
1411 1412 1413
		};
	}

J
Johannes Rieken 已提交
1414
	private executeTask(task: Task, resolver: ITaskResolver): Promise<ITaskSummary> {
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
		enum SaveBeforeRunConfigOptions {
			Always = 'always',
			Never = 'never',
			Prompt = 'prompt'
		}

		const saveBeforeRunTaskConfig: SaveBeforeRunConfigOptions = this.configurationService.getValue('task.saveBeforeRun');

		const execTask = async (task: Task, resolver: ITaskResolver): Promise<ITaskSummary> => {
			return ProblemMatcherRegistry.onReady().then(() => {
1425
				let executeResult = this.getTaskSystem().run(task, resolver);
A
Alex Ross 已提交
1426
				return this.handleExecuteResult(executeResult);
1427
			});
1428 1429 1430
		};

		const saveAllEditorsAndExecTask = async (task: Task, resolver: ITaskResolver): Promise<ITaskSummary> => {
1431
			return this.editorService.saveAll({ reason: SaveReason.AUTO }).then(() => {
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
				return execTask(task, resolver);
			});
		};

		const promptAsk = async (task: Task, resolver: ITaskResolver): Promise<ITaskSummary> => {
			const dialogOptions = await this.dialogService.show(
				Severity.Info,
				nls.localize('TaskSystem.saveBeforeRun.prompt.title', 'Save all editors?'),
				[nls.localize('saveBeforeRun.save', 'Save'), nls.localize('saveBeforeRun.dontSave', 'Don\'t save')],
				{
					detail: nls.localize('detail', "Do you want to save all editors before running the task?"),
					cancelId: 1
				}
			);

			if (dialogOptions.choice === 0) {
				return saveAllEditorsAndExecTask(task, resolver);
			} else {
				return execTask(task, resolver);
			}
		};

		if (saveBeforeRunTaskConfig === SaveBeforeRunConfigOptions.Never) {
			return execTask(task, resolver);
		} else if (saveBeforeRunTaskConfig === SaveBeforeRunConfigOptions.Prompt) {
			return promptAsk(task, resolver);
		} else {
			return saveAllEditorsAndExecTask(task, resolver);
		}
1461 1462
	}

1463
	private async handleExecuteResult(executeResult: ITaskExecuteResult): Promise<ITaskSummary> {
1464 1465 1466 1467 1468 1469 1470
		if (executeResult.task.taskLoadMessages && executeResult.task.taskLoadMessages.length > 0) {
			executeResult.task.taskLoadMessages.forEach(loadMessage => {
				this._outputChannel.append(loadMessage + '\n');
			});
			this.showOutput();
		}

1471
		await this.setRecentlyUsedTask(executeResult.task);
A
Alex Ross 已提交
1472 1473
		if (executeResult.kind === TaskExecuteKind.Active) {
			let active = executeResult.active;
1474
			if (active && active.same) {
1475 1476
				if (this._taskSystem?.isTaskVisible(executeResult.task)) {
					const message = nls.localize('TaskSystem.activeSame.noBackground', 'The task \'{0}\' is already active.', executeResult.task.getQualifiedLabel());
1477
					let lastInstance = this.getTaskSystem().getLastInstance(executeResult.task) ?? executeResult.task;
1478 1479 1480
					this.notificationService.prompt(Severity.Info, message,
						[{
							label: nls.localize('terminateTask', "Terminate Task"),
1481
							run: () => this.terminate(lastInstance)
1482 1483 1484
						},
						{
							label: nls.localize('restartTask', "Restart Task"),
1485
							run: () => this.restart(lastInstance)
1486 1487 1488
						}],
						{ sticky: true }
					);
A
Alex Ross 已提交
1489
				} else {
1490
					this._taskSystem?.revealTask(executeResult.task);
A
Alex Ross 已提交
1491 1492 1493 1494 1495 1496 1497 1498
				}
			} else {
				throw new TaskError(Severity.Warning, nls.localize('TaskSystem.active', 'There is already a task running. Terminate it first before executing another task.'), TaskErrors.RunningTask);
			}
		}
		return executeResult.promise;
	}

1499
	public restart(task: Task): void {
1500 1501 1502
		if (!this._taskSystem) {
			return;
		}
1503
		this._taskSystem.terminate(task).then((response) => {
1504
			if (response.success) {
A
Alex Ross 已提交
1505 1506 1507
				this.run(task).then(undefined, reason => {
					// eat the error, it has already been surfaced to the user and we don't care about it here
				});
1508
			} else {
A
Alex Ross 已提交
1509
				this.notificationService.warn(nls.localize('TaskSystem.restartFailed', 'Failed to terminate and restart task {0}', Types.isString(task) ? task : task.configurationProperties.name));
1510 1511 1512 1513 1514
			}
			return response;
		});
	}

J
Johannes Rieken 已提交
1515
	public terminate(task: Task): Promise<TaskTerminateResponse> {
1516
		if (!this._taskSystem) {
1517
			return Promise.resolve({ success: true, task: undefined });
1518
		}
1519
		return this._taskSystem.terminate(task);
1520 1521
	}

J
Johannes Rieken 已提交
1522
	public terminateAll(): Promise<TaskTerminateResponse[]> {
1523
		if (!this._taskSystem) {
1524
			return Promise.resolve<TaskTerminateResponse[]>([]);
1525
		}
1526
		return this._taskSystem.terminateAll();
1527 1528
	}

A
Alex Ross 已提交
1529 1530
	protected createTerminalTaskSystem(): ITaskSystem {
		return new TerminalTaskSystem(
1531
			this.terminalService, this.outputService, this.panelService, this.viewsService, this.markerService,
A
Alex Ross 已提交
1532 1533 1534
			this.modelService, this.configurationResolverService, this.telemetryService,
			this.contextService, this.environmentService,
			AbstractTaskService.OutputChannelId, this.fileService, this.terminalInstanceService,
1535
			this.pathService, this.viewDescriptorService,
A
Alex Ross 已提交
1536 1537 1538
			(workspaceFolder: IWorkspaceFolder) => {
				if (!workspaceFolder) {
					return undefined;
1539
				}
A
Alex Ross 已提交
1540
				return this._taskSystemInfos.get(workspaceFolder.uri.scheme);
D
Dirk Baeumer 已提交
1541
			}
A
Alex Ross 已提交
1542
		);
1543 1544
	}

A
Alex Ross 已提交
1545 1546
	protected abstract getTaskSystem(): ITaskSystem;

1547
	private getGroupedTasks(type?: string): Promise<TaskMap> {
1548
		const needsRecentTasksMigration = this.needsRecentTasksMigration();
1549
		return Promise.all([this.extensionService.activateByEvent('onCommand:workbench.action.tasks.runTask'), this.extensionService.whenInstalledExtensionsRegistered()]).then(() => {
1550 1551
			let validTypes: IStringDictionary<boolean> = Object.create(null);
			TaskDefinitionRegistry.all().forEach(definition => validTypes[definition.taskType] = true);
1552 1553
			validTypes['shell'] = true;
			validTypes['process'] = true;
B
Benjamin Pasero 已提交
1554
			return new Promise<TaskSet[]>(resolve => {
D
Dirk Baeumer 已提交
1555 1556
				let result: TaskSet[] = [];
				let counter: number = 0;
1557
				let done = (value: TaskSet | undefined) => {
D
Dirk Baeumer 已提交
1558 1559 1560 1561 1562 1563 1564
					if (value) {
						result.push(value);
					}
					if (--counter === 0) {
						resolve(result);
					}
				};
1565 1566
				let error = (error: any) => {
					try {
1567
						if (error && Types.isString(error.message)) {
1568
							this._outputChannel.append('Error: ');
1569
							this._outputChannel.append(error.message);
1570
							this._outputChannel.append('\n');
1571
							this.showOutput();
1572 1573
						} else {
							this._outputChannel.append('Unknown error received while collecting tasks from providers.\n');
1574
							this.showOutput();
1575 1576 1577 1578 1579
						}
					} finally {
						if (--counter === 0) {
							resolve(result);
						}
D
Dirk Baeumer 已提交
1580 1581
					}
				};
1582
				if (this.isProvideTasksEnabled() && (this.schemaVersion === JsonSchemaVersion.V2_0_0) && (this._providers.size > 0)) {
1583 1584 1585
					for (const [handle, provider] of this._providers) {
						if ((type === undefined) || (type === this._providerTypes.get(handle))) {
							counter++;
1586 1587 1588 1589 1590
							provider.provideTasks(validTypes).then((taskSet: TaskSet) => {
								// Check that the tasks provided are of the correct type
								for (const task of taskSet.tasks) {
									if (task.type !== this._providerTypes.get(handle)) {
										this._outputChannel.append(nls.localize('unexpectedTaskType', "The task provider for \"{0}\" tasks unexpectedly provided a task of type \"{1}\".\n", this._providerTypes.get(handle), task.type));
1591 1592 1593
										if ((task.type !== 'shell') && (task.type !== 'process')) {
											this.showOutput();
										}
1594 1595 1596 1597 1598
										break;
									}
								}
								return done(taskSet);
							}, error);
1599 1600
						}
					}
D
Dirk Baeumer 已提交
1601
				} else {
1602 1603
					resolve(result);
				}
D
Dirk Baeumer 已提交
1604
			});
D
Dirk Baeumer 已提交
1605
		}).then((contributedTaskSets) => {
1606 1607
			let result: TaskMap = new TaskMap();
			let contributedTasks: TaskMap = new TaskMap();
1608

D
Dirk Baeumer 已提交
1609 1610
			for (let set of contributedTaskSets) {
				for (let task of set.tasks) {
A
Alex Ross 已提交
1611
					let workspaceFolder = task.getWorkspaceFolder();
D
Dirk Baeumer 已提交
1612
					if (workspaceFolder) {
1613
						contributedTasks.add(workspaceFolder, task);
D
Dirk Baeumer 已提交
1614 1615 1616
					}
				}
			}
1617 1618 1619 1620

			return this.getWorkspaceTasks().then(async (customTasks) => {
				const customTasksKeyValuePairs = Array.from(customTasks);
				const customTasksPromises = customTasksKeyValuePairs.map(async ([key, folderTasks]) => {
D
Dirk Baeumer 已提交
1621
					let contributed = contributedTasks.get(key);
1622 1623
					if (!folderTasks.set) {
						if (contributed) {
1624
							result.add(key, ...contributed);
1625 1626 1627 1628
						}
						return;
					}

D
Dirk Baeumer 已提交
1629
					if (!contributed) {
1630
						result.add(key, ...folderTasks.set.tasks);
D
Dirk Baeumer 已提交
1631 1632 1633 1634 1635
					} else {
						let configurations = folderTasks.configurations;
						let legacyTaskConfigurations = folderTasks.set ? this.getLegacyTaskConfigurations(folderTasks.set) : undefined;
						let customTasksToDelete: Task[] = [];
						if (configurations || legacyTaskConfigurations) {
D
Dirk Baeumer 已提交
1636
							let unUsedConfigurations: Set<string> = new Set<string>();
1637 1638 1639
							if (configurations) {
								Object.keys(configurations.byIdentifier).forEach(key => unUsedConfigurations.add(key));
							}
D
Dirk Baeumer 已提交
1640 1641
							for (let task of contributed) {
								if (!ContributedTask.is(task)) {
1642 1643
									continue;
								}
D
Dirk Baeumer 已提交
1644 1645 1646
								if (configurations) {
									let configuringTask = configurations.byIdentifier[task.defines._key];
									if (configuringTask) {
D
Dirk Baeumer 已提交
1647
										unUsedConfigurations.delete(task.defines._key);
1648
										result.add(key, TaskConfig.createCustomTask(task, configuringTask));
D
Dirk Baeumer 已提交
1649
									} else {
1650
										result.add(key, task);
D
Dirk Baeumer 已提交
1651 1652 1653 1654
									}
								} else if (legacyTaskConfigurations) {
									let configuringTask = legacyTaskConfigurations[task.defines._key];
									if (configuringTask) {
1655
										result.add(key, TaskConfig.createCustomTask(task, configuringTask));
D
Dirk Baeumer 已提交
1656
										customTasksToDelete.push(configuringTask);
D
Dirk Baeumer 已提交
1657
									} else {
1658
										result.add(key, task);
D
Dirk Baeumer 已提交
1659 1660
									}
								} else {
1661
									result.add(key, task);
D
Dirk Baeumer 已提交
1662
								}
1663
							}
D
Dirk Baeumer 已提交
1664 1665 1666 1667 1668 1669 1670 1671 1672
							if (customTasksToDelete.length > 0) {
								let toDelete = customTasksToDelete.reduce<IStringDictionary<boolean>>((map, task) => {
									map[task._id] = true;
									return map;
								}, Object.create(null));
								for (let task of folderTasks.set.tasks) {
									if (toDelete[task._id]) {
										continue;
									}
1673
									result.add(key, task);
1674
								}
D
Dirk Baeumer 已提交
1675
							} else {
1676
								result.add(key, ...folderTasks.set.tasks);
1677
							}
1678 1679 1680 1681

							const unUsedConfigurationsAsArray = Array.from(unUsedConfigurations);

							const unUsedConfigurationPromises = unUsedConfigurationsAsArray.map(async (value) => {
1682
								let configuringTask = configurations!.byIdentifier[value];
A
Alex Ross 已提交
1683 1684 1685
								if (type && (type !== configuringTask.configures.type)) {
									return;
								}
1686 1687 1688 1689 1690

								for (const [handle, provider] of this._providers) {
									if (configuringTask.type === this._providerTypes.get(handle)) {
										try {
											const resolvedTask = await provider.resolveTask(configuringTask);
A
Alex Ross 已提交
1691
											if (resolvedTask && (resolvedTask._id === configuringTask._id)) {
1692 1693 1694 1695 1696 1697 1698 1699 1700
												result.add(key, TaskConfig.createCustomTask(resolvedTask, configuringTask));
												return;
											}
										} catch (error) {
											// Ignore errors. The task could not be provided by any of the providers.
										}
									}
								}

D
Dirk Baeumer 已提交
1701 1702
								this._outputChannel.append(nls.localize(
									'TaskService.noConfiguration',
1703 1704
									'Error: The {0} task detection didn\'t contribute a task for the following configuration:\n{1}\nThe task will be ignored.\n',
									configuringTask.configures.type,
D
Dirk Baeumer 已提交
1705 1706 1707 1708
									JSON.stringify(configuringTask._source.config.element, undefined, 4)
								));
								this.showOutput();
							});
1709 1710

							await Promise.all(unUsedConfigurationPromises);
D
Dirk Baeumer 已提交
1711
						} else {
1712 1713
							result.add(key, ...folderTasks.set.tasks);
							result.add(key, ...contributed);
1714 1715
						}
					}
D
Dirk Baeumer 已提交
1716
				});
1717 1718

				await Promise.all(customTasksPromises);
1719 1720
				if (needsRecentTasksMigration) {
					// At this point we have all the tasks and can migrate the recently used tasks.
1721
					await this.migrateRecentTasks(result.all());
1722
				}
1723 1724 1725
				return result;
			}, () => {
				// If we can't read the tasks.json file provide at least the contributed tasks
1726
				let result: TaskMap = new TaskMap();
D
Dirk Baeumer 已提交
1727
				for (let set of contributedTaskSets) {
1728
					for (let task of set.tasks) {
1729 1730 1731 1732
						const folder = task.getWorkspaceFolder();
						if (folder) {
							result.add(folder, task);
						}
1733
					}
D
Dirk Baeumer 已提交
1734
				}
1735 1736
				return result;
			});
1737 1738 1739
		});
	}

1740
	private getLegacyTaskConfigurations(workspaceTasks: TaskSet): IStringDictionary<CustomTask> | undefined {
1741
		let result: IStringDictionary<CustomTask> | undefined;
1742
		function getResult(): IStringDictionary<CustomTask> {
1743 1744 1745 1746
			if (result) {
				return result;
			}
			result = Object.create(null);
1747
			return result!;
1748 1749
		}
		for (let task of workspaceTasks.tasks) {
1750 1751 1752 1753 1754
			if (CustomTask.is(task)) {
				let commandName = task.command && task.command.name;
				// This is for backwards compatibility with the 0.1.0 task annotation code
				// if we had a gulp, jake or grunt command a task specification was a annotation
				if (commandName === 'gulp' || commandName === 'grunt' || commandName === 'jake') {
1755
					let identifier = NKeyedTaskIdentifier.create({
1756
						type: commandName,
A
Alex Ross 已提交
1757
						task: task.configurationProperties.name
1758
					});
1759 1760
					getResult()[identifier._key] = task;
				}
1761 1762 1763 1764 1765
			}
		}
		return result;
	}

J
Johannes Rieken 已提交
1766
	public getWorkspaceTasks(runSource: TaskRunSource = TaskRunSource.User): Promise<Map<string, WorkspaceFolderTaskResult>> {
1767 1768 1769
		if (this._workspaceTasksPromise) {
			return this._workspaceTasksPromise;
		}
1770
		this.updateWorkspaceTasks(runSource);
1771
		return this._workspaceTasksPromise!;
1772 1773
	}

A
Alex Ross 已提交
1774
	protected abstract updateWorkspaceTasks(runSource: TaskRunSource | void): void;
1775

A
Alex Ross 已提交
1776
	protected computeWorkspaceTasks(runSource: TaskRunSource = TaskRunSource.User): Promise<Map<string, WorkspaceFolderTaskResult>> {
D
Dirk Baeumer 已提交
1777
		if (this.workspaceFolders.length === 0) {
1778
			return Promise.resolve(new Map<string, WorkspaceFolderTaskResult>());
1779
		} else {
1780
			let promises: Promise<WorkspaceFolderTaskResult | undefined>[] = [];
D
Dirk Baeumer 已提交
1781
			for (let folder of this.workspaceFolders) {
1782
				promises.push(this.computeWorkspaceFolderTasks(folder, runSource).then((value) => value, () => undefined));
1783
			}
1784
			return Promise.all(promises).then(async (values) => {
1785 1786 1787 1788 1789 1790
				let result = new Map<string, WorkspaceFolderTaskResult>();
				for (let value of values) {
					if (value) {
						result.set(value.workspaceFolder.uri.toString(), value);
					}
				}
1791 1792
				const userTasks = await this.computeUserTasks(this.workspaceFolders[0], runSource).then((value) => value, () => undefined);
				if (userTasks) {
1793
					result.set(USER_TASKS_GROUP_KEY, userTasks);
1794 1795 1796 1797 1798
				}
				const workspaceFileTasks = await this.computeWorkspaceFileTasks(this.workspaceFolders[0], runSource).then((value) => value, () => undefined);
				if (workspaceFileTasks && this._workspace && this._workspace.configuration) {
					result.set(this._workspace.configuration.toString(), workspaceFileTasks);
				}
1799 1800 1801 1802 1803
				return result;
			});
		}
	}

A
Alex Ross 已提交
1804 1805 1806 1807
	public setJsonTasksSupported(areSupported: Promise<boolean>) {
		this._areJsonTasksSupportedPromise = areSupported;
	}

1808
	private computeWorkspaceFolderTasks(workspaceFolder: IWorkspaceFolder, runSource: TaskRunSource = TaskRunSource.User): Promise<WorkspaceFolderTaskResult> {
D
Dirk Baeumer 已提交
1809
		return (this.executionEngine === ExecutionEngine.Process
1810 1811 1812 1813
			? this.computeLegacyConfiguration(workspaceFolder)
			: this.computeConfiguration(workspaceFolder)).
			then((workspaceFolderConfiguration) => {
				if (!workspaceFolderConfiguration || !workspaceFolderConfiguration.config || workspaceFolderConfiguration.hasErrors) {
1814
					return Promise.resolve({ workspaceFolder, set: undefined, configurations: undefined, hasErrors: workspaceFolderConfiguration ? workspaceFolderConfiguration.hasErrors : false });
1815
				}
A
Alex Ross 已提交
1816
				return ProblemMatcherRegistry.onReady().then(async (): Promise<WorkspaceFolderTaskResult> => {
1817
					let taskSystemInfo: TaskSystemInfo | undefined = this._taskSystemInfos.get(workspaceFolder.uri.scheme);
1818
					let problemReporter = new ProblemReporter(this._outputChannel);
1819
					let parseResult = TaskConfig.parse(workspaceFolder, undefined, taskSystemInfo ? taskSystemInfo.platform : Platform.platform, workspaceFolderConfiguration.config!, problemReporter, TaskConfig.TaskConfigSource.TasksJson);
1820 1821 1822
					let hasErrors = false;
					if (!parseResult.validationStatus.isOK()) {
						hasErrors = true;
1823
						this.showOutput(runSource);
1824 1825 1826 1827 1828
					}
					if (problemReporter.status.isFatal()) {
						problemReporter.fatal(nls.localize('TaskSystem.configurationErrors', 'Error: the provided task configuration has validation errors and can\'t not be used. Please correct the errors first.'));
						return { workspaceFolder, set: undefined, configurations: undefined, hasErrors };
					}
1829
					let customizedTasks: { byIdentifier: IStringDictionary<ConfiguringTask>; } | undefined;
1830 1831 1832 1833 1834 1835 1836 1837
					if (parseResult.configured && parseResult.configured.length > 0) {
						customizedTasks = {
							byIdentifier: Object.create(null)
						};
						for (let task of parseResult.configured) {
							customizedTasks.byIdentifier[task.configures._key] = task;
						}
					}
A
Alex Ross 已提交
1838 1839 1840 1841
					if (!(await this._areJsonTasksSupportedPromise) && (parseResult.custom.length > 0)) {
						console.warn('Custom workspace tasks are not supported.');
					}
					return { workspaceFolder, set: { tasks: await this._areJsonTasksSupportedPromise ? parseResult.custom : [] }, configurations: customizedTasks, hasErrors };
1842 1843 1844 1845
				});
			});
	}

1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
	private testParseExternalConfig(config: TaskConfig.ExternalTaskRunnerConfiguration | undefined, location: string): { config: TaskConfig.ExternalTaskRunnerConfiguration | undefined, hasParseErrors: boolean } {
		if (!config) {
			return { config: undefined, hasParseErrors: false };
		}
		let parseErrors: string[] = (config as any).$parseErrors;
		if (parseErrors) {
			let isAffected = false;
			for (const parseError of parseErrors) {
				if (/tasks\.json$/.test(parseError)) {
					isAffected = true;
					break;
				}
			}
			if (isAffected) {
				this._outputChannel.append(nls.localize('TaskSystem.invalidTaskJsonOther', 'Error: The content of the tasks json in {0} has syntax errors. Please correct them before executing a task.\n', location));
				this.showOutput();
				return { config, hasParseErrors: true };
			}
		}
		return { config, hasParseErrors: false };
	}

	private async computeWorkspaceFileTasks(workspaceFolder: IWorkspaceFolder, runSource: TaskRunSource = TaskRunSource.User): Promise<WorkspaceFolderTaskResult> {
		if (this.executionEngine === ExecutionEngine.Process) {
			return this.emptyWorkspaceTaskResults(workspaceFolder);
		}
S
rename  
Sandeep Somavarapu 已提交
1872
		const configuration = this.testParseExternalConfig(this.configurationService.inspect<TaskConfig.ExternalTaskRunnerConfiguration>('tasks').workspaceValue, nls.localize('TasksSystem.locationWorkspaceConfig', 'workspace file'));
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
		let customizedTasks: { byIdentifier: IStringDictionary<ConfiguringTask>; } = {
			byIdentifier: Object.create(null)
		};

		const custom: CustomTask[] = [];
		await this.computeTasksForSingleConfig(workspaceFolder, configuration.config, runSource, custom, customizedTasks.byIdentifier, TaskConfig.TaskConfigSource.WorkspaceFile);
		const engine = configuration.config ? TaskConfig.ExecutionEngine.from(configuration.config) : ExecutionEngine.Terminal;
		if (engine === ExecutionEngine.Process) {
			this.notificationService.warn(nls.localize('TaskSystem.versionWorkspaceFile', 'Only tasks version 2.0.0 permitted in .codeworkspace.'));
			return this.emptyWorkspaceTaskResults(workspaceFolder);
		}
		return { workspaceFolder, set: { tasks: custom }, configurations: customizedTasks, hasErrors: configuration.hasParseErrors };
	}

	private async computeUserTasks(workspaceFolder: IWorkspaceFolder, runSource: TaskRunSource = TaskRunSource.User): Promise<WorkspaceFolderTaskResult> {
		if (this.executionEngine === ExecutionEngine.Process) {
			return this.emptyWorkspaceTaskResults(workspaceFolder);
		}
S
rename  
Sandeep Somavarapu 已提交
1891
		const configuration = this.testParseExternalConfig(this.configurationService.inspect<TaskConfig.ExternalTaskRunnerConfiguration>('tasks').userValue, nls.localize('TasksSystem.locationUserConfig', 'user settings'));
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
		let customizedTasks: { byIdentifier: IStringDictionary<ConfiguringTask>; } = {
			byIdentifier: Object.create(null)
		};

		const custom: CustomTask[] = [];
		await this.computeTasksForSingleConfig(workspaceFolder, configuration.config, runSource, custom, customizedTasks.byIdentifier, TaskConfig.TaskConfigSource.User);
		const engine = configuration.config ? TaskConfig.ExecutionEngine.from(configuration.config) : ExecutionEngine.Terminal;
		if (engine === ExecutionEngine.Process) {
			this.notificationService.warn(nls.localize('TaskSystem.versionSettings', 'Only tasks version 2.0.0 permitted in user settings.'));
			return this.emptyWorkspaceTaskResults(workspaceFolder);
		}
		return { workspaceFolder, set: { tasks: custom }, configurations: customizedTasks, hasErrors: configuration.hasParseErrors };
	}

	private emptyWorkspaceTaskResults(workspaceFolder: IWorkspaceFolder): WorkspaceFolderTaskResult {
		return { workspaceFolder, set: undefined, configurations: undefined, hasErrors: false };
	}

1910
	private async computeTasksForSingleConfig(workspaceFolder: IWorkspaceFolder, config: TaskConfig.ExternalTaskRunnerConfiguration | undefined, runSource: TaskRunSource, custom: CustomTask[], customized: IStringDictionary<ConfiguringTask>, source: TaskConfig.TaskConfigSource, isRecentTask: boolean = false): Promise<boolean> {
1911 1912 1913 1914 1915
		if (!config) {
			return false;
		}
		let taskSystemInfo: TaskSystemInfo | undefined = workspaceFolder ? this._taskSystemInfos.get(workspaceFolder.uri.scheme) : undefined;
		let problemReporter = new ProblemReporter(this._outputChannel);
1916
		let parseResult = TaskConfig.parse(workspaceFolder, this._workspace, taskSystemInfo ? taskSystemInfo.platform : Platform.platform, config, problemReporter, source, isRecentTask);
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
		let hasErrors = false;
		if (!parseResult.validationStatus.isOK()) {
			this.showOutput(runSource);
			hasErrors = true;
		}
		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 hasErrors;
		}
		if (parseResult.configured && parseResult.configured.length > 0) {
			for (let task of parseResult.configured) {
				customized[task.configures._key] = task;
			}
		}
		if (!(await this._areJsonTasksSupportedPromise) && (parseResult.custom.length > 0)) {
			console.warn('Custom workspace tasks are not supported.');
		} else {
			for (let task of parseResult.custom) {
				custom.push(task);
			}
		}
		return hasErrors;
	}

1941
	private computeConfiguration(workspaceFolder: IWorkspaceFolder): Promise<WorkspaceFolderConfigurationResult> {
1942
		let { config, hasParseErrors } = this.getConfiguration(workspaceFolder);
1943
		return Promise.resolve<WorkspaceFolderConfigurationResult>({ workspaceFolder, config, hasErrors: hasParseErrors });
1944 1945
	}

A
Alex Ross 已提交
1946
	protected abstract computeLegacyConfiguration(workspaceFolder: IWorkspaceFolder): Promise<WorkspaceFolderConfigurationResult>;
1947

1948
	private computeWorkspaceFolderSetup(): [IWorkspaceFolder[], IWorkspaceFolder[], ExecutionEngine, JsonSchemaVersion, IWorkspace | undefined] {
S
Sandeep Somavarapu 已提交
1949
		let workspaceFolders: IWorkspaceFolder[] = [];
D
Dirk Baeumer 已提交
1950
		let ignoredWorkspaceFolders: IWorkspaceFolder[] = [];
D
Dirk Baeumer 已提交
1951 1952
		let executionEngine = ExecutionEngine.Terminal;
		let schemaVersion = JsonSchemaVersion.V2_0_0;
1953
		let workspace: IWorkspace | undefined;
D
Dirk Baeumer 已提交
1954
		if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
S
Sandeep Somavarapu 已提交
1955
			let workspaceFolder: IWorkspaceFolder = this.contextService.getWorkspace().folders[0];
D
Dirk Baeumer 已提交
1956 1957 1958
			workspaceFolders.push(workspaceFolder);
			executionEngine = this.computeExecutionEngine(workspaceFolder);
			schemaVersion = this.computeJsonSchemaVersion(workspaceFolder);
D
Dirk Baeumer 已提交
1959
		} else if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
1960
			workspace = this.contextService.getWorkspace();
1961
			for (let workspaceFolder of this.contextService.getWorkspace().folders) {
D
Dirk Baeumer 已提交
1962
				if (schemaVersion === this.computeJsonSchemaVersion(workspaceFolder)) {
D
Dirk Baeumer 已提交
1963
					workspaceFolders.push(workspaceFolder);
1964
				} else {
D
Dirk Baeumer 已提交
1965
					ignoredWorkspaceFolders.push(workspaceFolder);
1966 1967
					this._outputChannel.append(nls.localize(
						'taskService.ignoreingFolder',
1968
						'Ignoring task configurations for workspace folder {0}. Multi folder workspace task support requires that all folders use task version 2.0.0\n',
1969
						workspaceFolder.uri.fsPath));
1970 1971 1972
				}
			}
		}
1973
		return [workspaceFolders, ignoredWorkspaceFolders, executionEngine, schemaVersion, workspace];
1974
	}
1975

S
Sandeep Somavarapu 已提交
1976
	private computeExecutionEngine(workspaceFolder: IWorkspaceFolder): ExecutionEngine {
1977
		let { config } = this.getConfiguration(workspaceFolder);
1978
		if (!config) {
1979
			return ExecutionEngine._default;
1980 1981 1982 1983
		}
		return TaskConfig.ExecutionEngine.from(config);
	}

S
Sandeep Somavarapu 已提交
1984
	private computeJsonSchemaVersion(workspaceFolder: IWorkspaceFolder): JsonSchemaVersion {
1985
		let { config } = this.getConfiguration(workspaceFolder);
1986 1987 1988 1989 1990 1991
		if (!config) {
			return JsonSchemaVersion.V2_0_0;
		}
		return TaskConfig.JsonSchemaVersion.from(config);
	}

1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
	protected getConfiguration(workspaceFolder: IWorkspaceFolder, source?: string): { config: TaskConfig.ExternalTaskRunnerConfiguration | undefined; hasParseErrors: boolean } {
		let result;
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
			result = undefined;
		} else {
			const wholeConfig = this.configurationService.inspect<TaskConfig.ExternalTaskRunnerConfiguration>('tasks', { resource: workspaceFolder.uri });
			switch (source) {
				case TaskSourceKind.User: result = Objects.deepClone(wholeConfig.userValue); break;
				case TaskSourceKind.Workspace: result = Objects.deepClone(wholeConfig.workspaceFolderValue); break;
				case TaskSourceKind.WorkspaceFile: result = Objects.deepClone(wholeConfig.workspaceValue); break;
				default: result = Objects.deepClone(wholeConfig.workspaceFolderValue);
			}
		}
2005
		if (!result) {
2006
			return { config: undefined, hasParseErrors: false };
2007 2008 2009 2010
		}
		let parseErrors: string[] = (result as any).$parseErrors;
		if (parseErrors) {
			let isAffected = false;
2011 2012
			for (const parseError of parseErrors) {
				if (/tasks\.json$/.test(parseError)) {
2013 2014 2015
					isAffected = true;
					break;
				}
2016
			}
2017
			if (isAffected) {
2018
				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'));
2019
				this.showOutput();
2020
				return { config: undefined, hasParseErrors: true };
2021
			}
2022 2023
		}
		return { config: result, hasParseErrors: false };
2024 2025
	}

2026
	public inTerminal(): boolean {
2027 2028 2029
		if (this._taskSystem) {
			return this._taskSystem instanceof TerminalTaskSystem;
		}
D
Dirk Baeumer 已提交
2030
		return this.executionEngine === ExecutionEngine.Terminal;
2031 2032
	}

2033
	public configureAction(): Action {
A
Alex Ross 已提交
2034
		const thisCapture: AbstractTaskService = this;
2035 2036
		return new class extends Action {
			constructor() {
2037
				super(ConfigureTaskAction.ID, ConfigureTaskAction.TEXT, undefined, true, () => { thisCapture.runConfigureTasks(); return Promise.resolve(undefined); });
2038 2039
			}
		};
2040 2041
	}

J
Johannes Rieken 已提交
2042
	public beforeShutdown(): boolean | Promise<boolean> {
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
		if (!this._taskSystem) {
			return false;
		}
		if (!this._taskSystem.isActiveSync()) {
			return false;
		}
		// The terminal service kills all terminal on shutdown. So there
		// is nothing we can do to prevent this here.
		if (this._taskSystem instanceof TerminalTaskSystem) {
			return false;
		}
2054

J
Johannes Rieken 已提交
2055
		let terminatePromise: Promise<IConfirmationResult>;
2056
		if (this._taskSystem.canAutoTerminate()) {
2057
			terminatePromise = Promise.resolve({ confirmed: true });
2058
		} else {
2059
			terminatePromise = this.dialogService.confirm({
2060 2061 2062 2063
				message: nls.localize('TaskSystem.runningTask', 'There is a task running. Do you want to terminate it?'),
				primaryButton: nls.localize({ key: 'TaskSystem.terminateTask', comment: ['&& denotes a mnemonic'] }, "&&Terminate Task"),
				type: 'question'
			});
E
Erich Gamma 已提交
2064
		}
2065

2066 2067
		return terminatePromise.then(res => {
			if (res.confirmed) {
2068
				return this._taskSystem!.terminateAll().then((responses) => {
2069
					let success = true;
2070
					let code: number | undefined = undefined;
2071 2072 2073 2074
					for (let response of responses) {
						success = success && response.success;
						// We only have a code in the old output runner which only has one task
						// So we can use the first code.
R
Rob Lourens 已提交
2075
						if (code === undefined && response.code !== undefined) {
2076 2077 2078 2079
							code = response.code;
						}
					}
					if (success) {
2080
						this._taskSystem = undefined;
2081 2082 2083
						this.disposeTaskSystemListeners();
						return false; // no veto
					} else if (code && code === TerminateResponseCode.ProcessNotFound) {
2084
						return this.dialogService.confirm({
2085 2086 2087
							message: nls.localize('TaskSystem.noProcess', 'The launched task doesn\'t exist anymore. If the task spawned background processes exiting VS Code might result in orphaned processes. To avoid this start the last background process with a wait flag.'),
							primaryButton: nls.localize({ key: 'TaskSystem.exitAnyways', comment: ['&& denotes a mnemonic'] }, "&&Exit Anyways"),
							type: 'info'
2088
						}).then(res => !res.confirmed);
2089 2090 2091 2092 2093 2094 2095 2096 2097
					}
					return true; // veto
				}, (err) => {
					return true; // veto
				});
			}

			return true; // veto
		});
E
Erich Gamma 已提交
2098 2099
	}

J
Johannes Rieken 已提交
2100
	private handleError(err: any): void {
E
Erich Gamma 已提交
2101 2102 2103
		let showOutput = true;
		if (err instanceof TaskError) {
			let buildError = <TaskError>err;
2104 2105 2106
			let needsConfig = buildError.code === TaskErrors.NotConfigured || buildError.code === TaskErrors.NoBuildTask || buildError.code === TaskErrors.NoTestTask;
			let needsTerminate = buildError.code === TaskErrors.RunningTask;
			if (needsConfig || needsTerminate) {
B
Benjamin Pasero 已提交
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
				this.notificationService.prompt(buildError.severity, buildError.message, [{
					label: needsConfig ? ConfigureTaskAction.TEXT : nls.localize('TerminateAction.label', "Terminate Task"),
					run: () => {
						if (needsConfig) {
							this.runConfigureTasks();
						} else {
							this.runTerminateCommand();
						}
					}
				}]);
E
Erich Gamma 已提交
2117
			} else {
2118
				this.notificationService.notify({ severity: buildError.severity, message: buildError.message });
E
Erich Gamma 已提交
2119 2120 2121
			}
		} else if (err instanceof Error) {
			let error = <Error>err;
2122
			this.notificationService.error(error.message);
2123
			showOutput = false;
E
Erich Gamma 已提交
2124
		} else if (Types.isString(err)) {
2125
			this.notificationService.error(<string>err);
E
Erich Gamma 已提交
2126
		} else {
2127
			this.notificationService.error(nls.localize('TaskSystem.unknownError', 'An error has occurred while running a task. See task log for details.'));
E
Erich Gamma 已提交
2128 2129
		}
		if (showOutput) {
2130
			this.showOutput();
E
Erich Gamma 已提交
2131 2132
		}
	}
2133 2134

	private canRunCommand(): boolean {
2135
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
2136 2137 2138 2139 2140
			this.notificationService.prompt(
				Severity.Info,
				nls.localize('TaskService.noWorkspace', "Tasks are only available on a workspace folder."),
				[{
					label: nls.localize('TaskService.learnMore', "Learn More"),
2141
					run: () => this.openerService.open(URI.parse('https://code.visualstudio.com/docs/editor/tasks'))
2142 2143
				}]
			);
2144 2145 2146 2147 2148
			return false;
		}
		return true;
	}

2149 2150 2151 2152
	private showDetail(): boolean {
		return this.configurationService.getValue<boolean>(QUICKOPEN_DETAIL_CONFIG);
	}

2153
	private async createTaskQuickPickEntries(tasks: Task[], group: boolean = false, sort: boolean = false, selectedEntry?: TaskQuickPickEntry, includeRecents: boolean = true): Promise<TaskQuickPickEntry[]> {
2154
		let count: { [key: string]: number; } = {};
R
Rob Lourens 已提交
2155
		if (tasks === undefined || tasks === null || tasks.length === 0) {
2156
			return [];
2157
		}
2158
		const TaskQuickPickEntry = (task: Task): TaskQuickPickEntry => {
2159
			let entryLabel = task._label;
2160 2161 2162
			if (count[task._id]) {
				entryLabel = entryLabel + ' (' + count[task._id].toString() + ')';
				count[task._id]++;
2163
			} else {
2164
				count[task._id] = 1;
2165 2166 2167
			}
			return { label: entryLabel, description: this.getTaskDescription(task), task, detail: this.showDetail() ? task.configurationProperties.detail : undefined };

2168
		};
C
Christof Marti 已提交
2169
		function fillEntries(entries: QuickPickInput<TaskQuickPickEntry>[], tasks: Task[], groupLabel: string): void {
C
Christof Marti 已提交
2170
			if (tasks.length) {
C
Christof Marti 已提交
2171
				entries.push({ type: 'separator', label: groupLabel });
2172
			}
2173
			for (let task of tasks) {
2174
				let entry: TaskQuickPickEntry = TaskQuickPickEntry(task);
2175
				entry.buttons = [{ iconClass: 'codicon-gear', tooltip: nls.localize('configureTask', "Configure Task") }];
2176 2177 2178 2179 2180
				if (selectedEntry && (task === selectedEntry.task)) {
					entries.unshift(selectedEntry);
				} else {
					entries.push(entry);
				}
2181 2182
			}
		}
2183
		let entries: TaskQuickPickEntry[];
2184 2185 2186
		if (group) {
			entries = [];
			if (tasks.length === 1) {
2187
				entries.push(TaskQuickPickEntry(tasks[0]));
2188
			} else {
2189
				let recentlyUsedTasks = await this.readRecentTasks();
2190
				let recent: Task[] = [];
2191
				let recentSet: Set<string> = new Set();
2192 2193 2194
				let configured: Task[] = [];
				let detected: Task[] = [];
				let taskMap: IStringDictionary<Task> = Object.create(null);
2195
				tasks.forEach(task => {
2196
					let key = task.getCommonTaskId();
2197 2198 2199 2200
					if (key) {
						taskMap[key] = task;
					}
				});
2201 2202 2203 2204 2205 2206 2207 2208
				recentlyUsedTasks.reverse().forEach(recentTask => {
					const key = recentTask.getCommonTaskId();
					if (key) {
						recentSet.add(key);
						let task = taskMap[key];
						if (task) {
							recent.push(task);
						}
2209 2210 2211
					}
				});
				for (let task of tasks) {
2212 2213
					let key = task.getCommonTaskId();
					if (!key || !recentSet.has(key)) {
2214
						if ((task._source.kind === TaskSourceKind.Workspace) || (task._source.kind === TaskSourceKind.User)) {
2215 2216 2217 2218 2219 2220
							configured.push(task);
						} else {
							detected.push(task);
						}
					}
				}
2221
				const sorter = this.createSorter();
2222 2223 2224
				if (includeRecents) {
					fillEntries(entries, recent, nls.localize('recentlyUsed', 'recently used tasks'));
				}
2225
				configured = configured.sort((a, b) => sorter.compare(a, b));
C
Christof Marti 已提交
2226
				fillEntries(entries, configured, nls.localize('configured', 'configured tasks'));
2227
				detected = detected.sort((a, b) => sorter.compare(a, b));
C
Christof Marti 已提交
2228
				fillEntries(entries, detected, nls.localize('detected', 'detected tasks'));
2229 2230 2231
			}
		} else {
			if (sort) {
2232 2233
				const sorter = this.createSorter();
				tasks = tasks.sort((a, b) => sorter.compare(a, b));
2234
			}
2235
			entries = tasks.map<TaskQuickPickEntry>(task => TaskQuickPickEntry(task));
2236
		}
2237
		count = {};
2238 2239 2240
		return entries;
	}

A
Alex Ross 已提交
2241
	private async showTwoLevelQuickPick(placeHolder: string, defaultEntry?: TaskQuickPickEntry) {
2242
		return TaskQuickPick.show(this, this.configurationService, this.quickInputService, this.notificationService, placeHolder, defaultEntry);
A
Alex Ross 已提交
2243 2244
	}

2245
	private async showQuickPick(tasks: Promise<Task[]> | Task[], placeHolder: string, defaultEntry?: TaskQuickPickEntry, group: boolean = false, sort: boolean = false, selectedEntry?: TaskQuickPickEntry, additionalEntries?: TaskQuickPickEntry[]): Promise<TaskQuickPickEntry | undefined | null> {
2246 2247
		const tokenSource = new CancellationTokenSource();
		const cancellationToken: CancellationToken = tokenSource.token;
2248
		let _createEntries = new Promise<QuickPickInput<TaskQuickPickEntry>[]>((resolve) => {
2249
			if (Array.isArray(tasks)) {
2250
				resolve(this.createTaskQuickPickEntries(tasks, group, sort, selectedEntry));
2251
			} else {
2252
				resolve(tasks.then((tasks) => this.createTaskQuickPickEntries(tasks, group, sort, selectedEntry)));
2253
			}
2254 2255
		});

2256
		const timeout: boolean = await Promise.race([new Promise<boolean>(async (resolve) => {
2257 2258
			await _createEntries;
			resolve(false);
2259
		}), new Promise<boolean>((resolve) => {
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
			const timer = setTimeout(() => {
				clearTimeout(timer);
				resolve(true);
			}, 200);
		})]);

		if (!timeout && ((await _createEntries).length === 1) && this.configurationService.getValue<boolean>(QUICKOPEN_SKIP_CONFIG)) {
			return (<TaskQuickPickEntry>(await _createEntries)[0]);
		}

		const pickEntries = _createEntries.then((entries) => {
2271 2272 2273
			if ((entries.length === 1) && this.configurationService.getValue<boolean>(QUICKOPEN_SKIP_CONFIG)) {
				tokenSource.cancel();
			} else if ((entries.length === 0) && defaultEntry) {
2274
				entries.push(defaultEntry);
A
Alex Ross 已提交
2275 2276
			} else if (entries.length > 1 && additionalEntries && additionalEntries.length > 0) {
				entries.push({ type: 'separator', label: '' });
2277 2278
				entries.push(additionalEntries[0]);
			}
2279
			return entries;
2280
		});
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292

		const picker: IQuickPick<TaskQuickPickEntry> = this.quickInputService.createQuickPick();
		picker.placeholder = placeHolder;
		picker.matchOnDescription = true;

		picker.onDidTriggerItemButton(context => {
			let task = context.item.task;
			this.quickInputService.cancel();
			if (ContributedTask.is(task)) {
				this.customize(task, undefined, true);
			} else if (CustomTask.is(task)) {
				this.openConfig(task);
2293
			}
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
		});
		picker.busy = true;
		pickEntries.then(entries => {
			picker.busy = false;
			picker.items = entries;
		});
		picker.show();

		return new Promise<TaskQuickPickEntry | undefined | null>(resolve => {
			this._register(picker.onDidAccept(async () => {
				let selection = picker.selectedItems ? picker.selectedItems[0] : undefined;
				if (cancellationToken.isCancellationRequested) {
					// canceled when there's only one task
					const task = (await pickEntries)[0];
					if ((<any>task).task) {
						selection = <TaskQuickPickEntry>task;
					}
				}
				picker.dispose();
				if (!selection) {
					resolve();
				}
				resolve(selection);
			}));
M
Matt Bierner 已提交
2318
		});
2319 2320
	}

2321 2322 2323 2324
	private needsRecentTasksMigration(): boolean {
		return (this.getRecentlyUsedTasksV1().size > 0) && (this.getRecentlyUsedTasks().size === 0);
	}

2325
	public async migrateRecentTasks(tasks: Task[]) {
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
		if (!this.needsRecentTasksMigration()) {
			return;
		}
		let recentlyUsedTasks = this.getRecentlyUsedTasksV1();
		let taskMap: IStringDictionary<Task> = Object.create(null);
		tasks.forEach(task => {
			let key = task.getRecentlyUsedKey();
			if (key) {
				taskMap[key] = task;
			}
		});
2337
		const reversed = [...recentlyUsedTasks.keys()].reverse();
2338
		for (const key in reversed) {
2339 2340
			let task = taskMap[key];
			if (task) {
2341
				await this.setRecentlyUsedTask(task);
2342
			}
2343
		}
2344 2345 2346
		this.storageService.remove(AbstractTaskService.RecentlyUsedTasks_Key, StorageScope.WORKSPACE);
	}

J
Johannes Rieken 已提交
2347
	private showIgnoredFoldersMessage(): Promise<void> {
D
Dirk Baeumer 已提交
2348
		if (this.ignoredWorkspaceFolders.length === 0 || !this.showIgnoreMessage) {
2349
			return Promise.resolve(undefined);
D
Dirk Baeumer 已提交
2350 2351
		}

2352 2353 2354 2355
		this.notificationService.prompt(
			Severity.Info,
			nls.localize('TaskService.ignoredFolder', 'The following workspace folders are ignored since they use task version 0.1.0: {0}', this.ignoredWorkspaceFolders.map(f => f.name).join(', ')),
			[{
H
Howard Hung 已提交
2356
				label: nls.localize('TaskService.notAgain', "Don't Show Again"),
2357 2358
				isSecondary: true,
				run: () => {
A
Alex Ross 已提交
2359
					this.storageService.store(AbstractTaskService.IgnoreTask010DonotShowAgain_key, true, StorageScope.WORKSPACE);
2360
					this._showIgnoreMessage = false;
2361 2362 2363
				}
			}]
		);
2364

2365
		return Promise.resolve(undefined);
D
Dirk Baeumer 已提交
2366 2367
	}

2368
	private runTaskCommand(arg?: any): void {
2369 2370 2371
		if (!this.canRunCommand()) {
			return;
		}
2372
		let identifier = this.getTaskIdentifier(arg);
R
Rob Lourens 已提交
2373
		if (identifier !== undefined) {
A
Alex Ross 已提交
2374
			this.getGroupedTasks().then(async (grouped) => {
2375
				let resolver = this.createResolver(grouped);
2376 2377 2378 2379 2380 2381 2382
				let folderURIs: (URI | string)[] = this.contextService.getWorkspace().folders.map(folder => folder.uri);
				if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
					folderURIs.push(this.contextService.getWorkspace().configuration!);
				}
				folderURIs.push(USER_TASKS_GROUP_KEY);
				for (let uri of folderURIs) {
					let task = await resolver.resolve(uri, identifier);
2383
					if (task) {
A
Alex Ross 已提交
2384 2385 2386
						this.run(task).then(undefined, reason => {
							// eat the error, it has already been surfaced to the user and we don't care about it here
						});
2387 2388
						return;
					}
2389
				}
2390
				this.doRunTaskCommand(grouped.all());
2391
			}, () => {
2392
				this.doRunTaskCommand();
2393 2394
			});
		} else {
2395
			this.doRunTaskCommand();
2396 2397 2398
		}
	}

2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
	private tasksAndGroupedTasks(filter?: TaskFilter): { tasks: Promise<Task[]>, grouped: Promise<TaskMap> } {
		if (!this.versionAndEngineCompatible(filter)) {
			return { tasks: Promise.resolve<Task[]>([]), grouped: Promise.resolve(new TaskMap()) };
		}
		const grouped = this.getGroupedTasks(filter ? filter.type : undefined);
		const tasks = grouped.then((map) => {
			if (!filter || !filter.type) {
				return map.all();
			}
			let result: Task[] = [];
			map.forEach((tasks) => {
				for (let task of tasks) {
					if (ContributedTask.is(task) && task.defines.type === filter.type) {
						result.push(task);
					} else if (CustomTask.is(task)) {
						if (task.type === filter.type) {
							result.push(task);
						} else {
							let customizes = task.customizes();
							if (customizes && customizes.type === filter.type) {
								result.push(task);
							}
						}
D
Dirk Baeumer 已提交
2422
					}
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
				}
			});
			return result;
		});
		return { tasks, grouped };
	}

	private doRunTaskCommand(tasks?: Task[]): void {
		const pickThen = (task: Task | undefined | null) => {
			if (task === undefined) {
				return;
			}
			if (task === null) {
				this.runConfigureTasks();
			} else {
				this.run(task, { attachProblemMatcher: true }, TaskRunSource.User).then(undefined, reason => {
					// eat the error, it has already been surfaced to the user and we don't care about it here
D
Dirk Baeumer 已提交
2440
				});
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
			}
		};

		const placeholder = nls.localize('TaskService.pickRunTask', 'Select the task to run');

		this.showIgnoredFoldersMessage().then(() => {
			if (this.configurationService.getValue(USE_SLOW_PICKER)) {
				let taskResult: { tasks: Promise<Task[]>, grouped: Promise<TaskMap> } | undefined = undefined;
				if (!tasks) {
					taskResult = this.tasksAndGroupedTasks();
				}
				this.showQuickPick(tasks ? tasks : taskResult!.tasks, placeholder,
					{
						label: nls.localize('TaskService.noEntryToRunSlow', 'No task to run found. Configure Tasks...'),
						task: null
					},
					true).
					then((entry) => {
						return pickThen(entry ? entry.task : undefined);
					});
			} else {
				this.showTwoLevelQuickPick(placeholder,
					{
						label: nls.localize('TaskService.noEntryToRun', 'No configured tasks. Configure Tasks...'),
						task: null
					}).
					then(pickThen);
			}
D
Dirk Baeumer 已提交
2469
		});
2470 2471
	}

2472
	private reRunTaskCommand(): void {
A
Alex Ross 已提交
2473 2474 2475 2476 2477
		if (!this.canRunCommand()) {
			return;
		}

		ProblemMatcherRegistry.onReady().then(() => {
2478
			return this.editorService.saveAll({ reason: SaveReason.AUTO }).then(() => { // make sure all dirty editors are saved
A
Alex Ross 已提交
2479 2480 2481 2482 2483
				let executeResult = this.getTaskSystem().rerun();
				if (executeResult) {
					return this.handleExecuteResult(executeResult);
				} else {
					this.doRunTaskCommand();
2484
					return Promise.resolve(undefined);
A
Alex Ross 已提交
2485 2486 2487 2488 2489
				}
			});
		});
	}

2490 2491 2492 2493 2494
	private splitPerGroupType(tasks: Task[]): { none: Task[], defaults: Task[], users: Task[] } {
		let none: Task[] = [];
		let defaults: Task[] = [];
		let users: Task[] = [];
		for (let task of tasks) {
A
Alex Ross 已提交
2495
			if (task.configurationProperties.groupType === GroupType.default) {
2496
				defaults.push(task);
A
Alex Ross 已提交
2497
			} else if (task.configurationProperties.groupType === GroupType.user) {
2498 2499 2500 2501 2502 2503 2504 2505
				users.push(task);
			} else {
				none.push(task);
			}
		}
		return { none, defaults, users };
	}

2506 2507 2508 2509
	private runBuildCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2510
		if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
2511 2512 2513
			this.build();
			return;
		}
2514 2515 2516 2517 2518
		let options: IProgressOptions = {
			location: ProgressLocation.Window,
			title: nls.localize('TaskService.fetchingBuildTasks', 'Fetching build tasks...')
		};
		let promise = this.getTasksForGroup(TaskGroup.Build).then((tasks) => {
2519
			if (tasks.length > 0) {
D
Dirk Baeumer 已提交
2520
				let { defaults, users } = this.splitPerGroupType(tasks);
2521
				if (defaults.length === 1) {
A
Alex Ross 已提交
2522 2523 2524
					this.run(defaults[0]).then(undefined, reason => {
						// eat the error, it has already been surfaced to the user and we don't care about it here
					});
2525
					return;
2526 2527
				} else if (defaults.length + users.length > 0) {
					tasks = defaults.concat(users);
D
Dirk Baeumer 已提交
2528 2529
				}
			}
D
Dirk Baeumer 已提交
2530 2531 2532 2533
			this.showIgnoredFoldersMessage().then(() => {
				this.showQuickPick(tasks,
					nls.localize('TaskService.pickBuildTask', 'Select the build task to run'),
					{
2534
						label: nls.localize('TaskService.noBuildTask', 'No build task to run found. Configure Build Task...'),
D
Dirk Baeumer 已提交
2535 2536
						task: null
					},
2537 2538
					true).then((entry) => {
						let task: Task | undefined | null = entry ? entry.task : undefined;
R
Rob Lourens 已提交
2539
						if (task === undefined) {
D
Dirk Baeumer 已提交
2540 2541 2542
							return;
						}
						if (task === null) {
2543
							this.runConfigureDefaultBuildTask();
D
Dirk Baeumer 已提交
2544 2545
							return;
						}
A
Alex Ross 已提交
2546 2547 2548
						this.run(task, { attachProblemMatcher: true }).then(undefined, reason => {
							// eat the error, it has already been surfaced to the user and we don't care about it here
						});
D
Dirk Baeumer 已提交
2549 2550
					});
			});
2551
		});
2552
		this.progressService.withProgress(options, () => promise);
2553 2554 2555 2556 2557 2558
	}

	private runTestCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2559
		if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
2560
			this.runTest();
2561 2562
			return;
		}
2563 2564 2565 2566 2567
		let options: IProgressOptions = {
			location: ProgressLocation.Window,
			title: nls.localize('TaskService.fetchingTestTasks', 'Fetching test tasks...')
		};
		let promise = this.getTasksForGroup(TaskGroup.Test).then((tasks) => {
2568
			if (tasks.length > 0) {
D
Dirk Baeumer 已提交
2569
				let { defaults, users } = this.splitPerGroupType(tasks);
2570
				if (defaults.length === 1) {
A
Alex Ross 已提交
2571 2572 2573
					this.run(defaults[0]).then(undefined, reason => {
						// eat the error, it has already been surfaced to the user and we don't care about it here
					});
2574
					return;
2575 2576
				} else if (defaults.length + users.length > 0) {
					tasks = defaults.concat(users);
D
Dirk Baeumer 已提交
2577 2578
				}
			}
D
Dirk Baeumer 已提交
2579 2580 2581 2582 2583 2584 2585
			this.showIgnoredFoldersMessage().then(() => {
				this.showQuickPick(tasks,
					nls.localize('TaskService.pickTestTask', 'Select the test task to run'),
					{
						label: nls.localize('TaskService.noTestTaskTerminal', 'No test task to run found. Configure Tasks...'),
						task: null
					}, true
2586 2587
				).then((entry) => {
					let task: Task | undefined | null = entry ? entry.task : undefined;
R
Rob Lourens 已提交
2588
					if (task === undefined) {
D
Dirk Baeumer 已提交
2589 2590 2591 2592 2593 2594
						return;
					}
					if (task === null) {
						this.runConfigureTasks();
						return;
					}
A
Alex Ross 已提交
2595 2596 2597
					this.run(task).then(undefined, reason => {
						// eat the error, it has already been surfaced to the user and we don't care about it here
					});
D
Dirk Baeumer 已提交
2598
				});
2599
			});
2600
		});
2601
		this.progressService.withProgress(options, () => promise);
2602 2603
	}

2604
	private runTerminateCommand(arg?: any): void {
2605 2606 2607
		if (!this.canRunCommand()) {
			return;
		}
2608 2609 2610 2611
		if (arg === 'terminateAll') {
			this.terminateAll();
			return;
		}
J
Johannes Rieken 已提交
2612
		let runQuickPick = (promise?: Promise<Task[]>) => {
2613
			this.showQuickPick(promise || this.getActiveTasks(),
A
Alex Ross 已提交
2614
				nls.localize('TaskService.taskToTerminate', 'Select a task to terminate'),
2615 2616
				{
					label: nls.localize('TaskService.noTaskRunning', 'No task is currently running'),
2617
					task: undefined
2618
				},
2619 2620 2621
				false, true,
				undefined,
				[{
A
Alex Ross 已提交
2622
					label: nls.localize('TaskService.terminateAllRunningTasks', 'All Running Tasks'),
2623 2624 2625 2626 2627 2628 2629 2630
					id: 'terminateAll',
					task: undefined
				}]
			).then(entry => {
				if (entry && entry.id === 'terminateAll') {
					this.terminateAll();
				}
				let task: Task | undefined | null = entry ? entry.task : undefined;
R
Rob Lourens 已提交
2631
				if (task === undefined || task === null) {
2632 2633
					return;
				}
2634
				this.terminate(task);
2635
			});
2636 2637 2638
		};
		if (this.inTerminal()) {
			let identifier = this.getTaskIdentifier(arg);
J
Johannes Rieken 已提交
2639
			let promise: Promise<Task[]>;
R
Rob Lourens 已提交
2640
			if (identifier !== undefined) {
2641 2642 2643
				promise = this.getActiveTasks();
				promise.then((tasks) => {
					for (let task of tasks) {
A
Alex Ross 已提交
2644
						if (task.matches(identifier)) {
2645 2646 2647 2648 2649 2650 2651 2652 2653
							this.terminate(task);
							return;
						}
					}
					runQuickPick(promise);
				});
			} else {
				runQuickPick();
			}
2654 2655 2656
		} else {
			this.isActive().then((active) => {
				if (active) {
2657 2658 2659
					this.terminateAll().then((responses) => {
						// the output runner has only one task
						let response = responses[0];
2660
						if (response.success) {
2661 2662 2663
							return;
						}
						if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
2664
							this.notificationService.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.'));
2665
						} else {
2666
							this.notificationService.error(nls.localize('TerminateAction.failed', 'Failed to terminate running task'));
2667 2668 2669 2670 2671 2672
						}
					});
				}
			});
		}
	}
2673

2674
	private runRestartTaskCommand(arg?: any): void {
2675 2676 2677
		if (!this.canRunCommand()) {
			return;
		}
J
Johannes Rieken 已提交
2678
		let runQuickPick = (promise?: Promise<Task[]>) => {
2679
			this.showQuickPick(promise || this.getActiveTasks(),
2680
				nls.localize('TaskService.taskToRestart', 'Select the task to restart'),
2681 2682 2683 2684 2685
				{
					label: nls.localize('TaskService.noTaskToRestart', 'No task to restart'),
					task: null
				},
				false, true
2686 2687
			).then(entry => {
				let task: Task | undefined | null = entry ? entry.task : undefined;
R
Rob Lourens 已提交
2688
				if (task === undefined || task === null) {
2689 2690
					return;
				}
2691
				this.restart(task);
2692
			});
2693 2694 2695
		};
		if (this.inTerminal()) {
			let identifier = this.getTaskIdentifier(arg);
J
Johannes Rieken 已提交
2696
			let promise: Promise<Task[]>;
R
Rob Lourens 已提交
2697
			if (identifier !== undefined) {
2698 2699 2700
				promise = this.getActiveTasks();
				promise.then((tasks) => {
					for (let task of tasks) {
A
Alex Ross 已提交
2701
						if (task.matches(identifier)) {
2702 2703 2704 2705 2706 2707 2708 2709 2710
							this.restart(task);
							return;
						}
					}
					runQuickPick(promise);
				});
			} else {
				runQuickPick();
			}
2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
		} else {
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
					return;
				}
				let task = activeTasks[0];
				this.restart(task);
			});
		}
	}
2721

2722
	private getTaskIdentifier(arg?: any): string | KeyedTaskIdentifier | undefined {
2723
		let result: string | KeyedTaskIdentifier | undefined = undefined;
2724 2725 2726 2727 2728 2729 2730 2731
		if (Types.isString(arg)) {
			result = arg;
		} else if (arg && Types.isString((arg as TaskIdentifier).type)) {
			result = TaskDefinition.createTaskIdentifier(arg as TaskIdentifier, console);
		}
		return result;
	}

2732 2733 2734 2735
	private configHasTasks(taskConfig?: TaskConfig.ExternalTaskRunnerConfiguration): boolean {
		return !!taskConfig && !!taskConfig.tasks && taskConfig.tasks.length > 0;
	}

2736
	private openTaskFile(resource: URI, taskSource: string) {
2737
		let configFileCreated = false;
2738 2739 2740 2741 2742 2743
		this.fileService.resolve(resource).then((stat) => stat, () => undefined).then(async (stat) => {
			const fileExists: boolean = !!stat;
			const configValue = this.configurationService.inspect<TaskConfig.ExternalTaskRunnerConfiguration>('tasks');
			let tasksExistInFile: boolean;
			let target: ConfigurationTarget;
			switch (taskSource) {
2744 2745 2746
				case TaskSourceKind.User: tasksExistInFile = this.configHasTasks(configValue.userValue); target = ConfigurationTarget.USER; break;
				case TaskSourceKind.WorkspaceFile: tasksExistInFile = this.configHasTasks(configValue.workspaceValue); target = ConfigurationTarget.WORKSPACE; break;
				default: tasksExistInFile = this.configHasTasks(configValue.value); target = ConfigurationTarget.WORKSPACE_FOLDER;
2747 2748 2749 2750 2751
			}
			let content;
			if (!tasksExistInFile) {
				const pickTemplateResult = await this.quickInputService.pick(getTaskTemplates(), { placeHolder: nls.localize('TaskService.template', 'Select a Task Template') });
				if (!pickTemplateResult) {
2752 2753
					return Promise.resolve(undefined);
				}
2754
				content = pickTemplateResult.content;
2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
				let editorConfig = this.configurationService.getValue<any>();
				if (editorConfig.editor.insertSpaces) {
					content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + strings.repeat(' ', s2.length * editorConfig.editor.tabSize));
				}
				configFileCreated = true;
				type TaskServiceTemplateClassification = {
					templateId?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
					autoDetect: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
				};
				type TaskServiceEvent = {
					templateId?: string;
					autoDetect: boolean;
				};
2768 2769 2770 2771 2772 2773 2774
				this.telemetryService.publicLog2<TaskServiceEvent, TaskServiceTemplateClassification>('taskService.template', {
					templateId: pickTemplateResult.id,
					autoDetect: pickTemplateResult.autoDetect
				});
			}

			if (!fileExists && content) {
2775 2776 2777
				return this.textFileService.create(resource, content).then((result): URI => {
					return result.resource;
				});
2778 2779 2780 2781 2782 2783 2784
			} else if (fileExists && (tasksExistInFile || content)) {
				if (content) {
					this.configurationService.updateValue('tasks', json.parse(content), target);
				}
				return stat?.resource;
			}
			return undefined;
2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
		}).then((resource) => {
			if (!resource) {
				return;
			}
			this.editorService.openEditor({
				resource,
				options: {
					pinned: configFileCreated // pin only if config file is created #8727
				}
			});
		});
	}

A
Alex Ross 已提交
2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
	private isTaskEntry(value: IQuickPickItem): value is IQuickPickItem & { task: Task } {
		let candidate: IQuickPickItem & { task: Task } = value as any;
		return candidate && !!candidate.task;
	}

	private configureTask(task: Task) {
		if (ContributedTask.is(task)) {
			this.customize(task, undefined, true);
		} else if (CustomTask.is(task)) {
			this.openConfig(task);
		} else if (ConfiguringTask.is(task)) {
			// Do nothing.
		}
	}

2813
	private handleSelection(selection: TaskQuickPickEntryType | undefined) {
A
Alex Ross 已提交
2814 2815 2816 2817 2818 2819
		if (!selection) {
			return;
		}
		if (this.isTaskEntry(selection)) {
			this.configureTask(selection.task);
		} else {
2820
			this.openTaskFile(selection.folder.toResource('.vscode/tasks.json'), TaskSourceKind.Workspace);
A
Alex Ross 已提交
2821 2822
		}
	}
2823

A
Alex Ross 已提交
2824
	public getTaskDescription(task: Task | ConfiguringTask): string | undefined {
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
		let description: string | undefined;
		if (task._source.kind === TaskSourceKind.User) {
			description = nls.localize('taskQuickPick.userSettings', 'User Settings');
		} else if (task._source.kind === TaskSourceKind.WorkspaceFile) {
			description = task.getWorkspaceFileName();
		} else if (this.needsFolderQualification()) {
			let workspaceFolder = task.getWorkspaceFolder();
			if (workspaceFolder) {
				description = workspaceFolder.name;
			}
		}
		return description;
	}

2839
	private async runConfigureTasks(): Promise<void> {
2840 2841 2842
		if (!this.canRunCommand()) {
			return undefined;
		}
J
Johannes Rieken 已提交
2843
		let taskPromise: Promise<TaskMap>;
D
Dirk Baeumer 已提交
2844
		if (this.schemaVersion === JsonSchemaVersion.V2_0_0) {
2845 2846
			taskPromise = this.getGroupedTasks();
		} else {
2847
			taskPromise = Promise.resolve(new TaskMap());
2848 2849
		}

2850
		let stats = this.contextService.getWorkspace().folders.map<Promise<IFileStat | undefined>>((folder) => {
B
Benjamin Pasero 已提交
2851
			return this.fileService.resolve(folder.toResource('.vscode/tasks.json')).then(stat => stat, () => undefined);
2852 2853 2854 2855
		});

		let createLabel = nls.localize('TaskService.createJsonFile', 'Create tasks.json file from template');
		let openLabel = nls.localize('TaskService.openJsonFile', 'Open tasks.json file');
2856 2857
		const tokenSource = new CancellationTokenSource();
		const cancellationToken: CancellationToken = tokenSource.token;
2858
		let entries = Promise.all(stats).then((stats) => {
2859
			return taskPromise.then((taskMap) => {
A
Alex Ross 已提交
2860
				let entries: QuickPickInput<TaskQuickPickEntryType>[] = [];
2861
				let needsCreateOrOpen: boolean = true;
2862
				if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY) {
2863 2864 2865
					let tasks = taskMap.all();
					if (tasks.length > 0) {
						tasks = tasks.sort((a, b) => a._label.localeCompare(b._label));
2866
						for (let task of tasks) {
2867
							entries.push({ label: task._label, task, description: this.getTaskDescription(task) });
2868 2869 2870 2871 2872 2873
							if (!ContributedTask.is(task)) {
								needsCreateOrOpen = false;
							}
						}
					}
					if (needsCreateOrOpen) {
R
Rob Lourens 已提交
2874
						let label = stats[0] !== undefined ? openLabel : createLabel;
C
Christof Marti 已提交
2875
						if (entries.length) {
C
Christof Marti 已提交
2876
							entries.push({ type: 'separator' });
C
Christof Marti 已提交
2877 2878
						}
						entries.push({ label, folder: this.contextService.getWorkspace().folders[0] });
2879 2880 2881 2882 2883 2884 2885 2886 2887
					}
				} else {
					let folders = this.contextService.getWorkspace().folders;
					let index = 0;
					for (let folder of folders) {
						let tasks = taskMap.get(folder);
						if (tasks.length > 0) {
							tasks = tasks.slice().sort((a, b) => a._label.localeCompare(b._label));
							for (let i = 0; i < tasks.length; i++) {
2888
								let entry: TaskQuickPickEntryType = { label: tasks[i]._label, task: tasks[i], description: this.getTaskDescription(tasks[i]) };
2889
								if (i === 0) {
C
Christof Marti 已提交
2890
									entries.push({ type: 'separator', label: folder.name });
2891 2892 2893 2894
								}
								entries.push(entry);
							}
						} else {
R
Rob Lourens 已提交
2895
							let label = stats[index] !== undefined ? openLabel : createLabel;
A
Alex Ross 已提交
2896
							let entry: TaskQuickPickEntryType = { label, folder: folder };
C
Christof Marti 已提交
2897
							entries.push({ type: 'separator', label: folder.name });
2898 2899 2900 2901 2902
							entries.push(entry);
						}
						index++;
					}
				}
2903
				if ((entries.length === 1) && !needsCreateOrOpen) {
2904 2905
					tokenSource.cancel();
				}
2906 2907 2908 2909
				return entries;
			});
		});

2910
		const timeout: boolean = await Promise.race([new Promise<boolean>(async (resolve) => {
2911 2912
			await entries;
			resolve(false);
2913
		}), new Promise<boolean>((resolve) => {
2914 2915 2916 2917 2918 2919 2920
			const timer = setTimeout(() => {
				clearTimeout(timer);
				resolve(true);
			}, 200);
		})]);

		if (!timeout && ((await entries).length === 1) && this.configurationService.getValue<boolean>(QUICKOPEN_SKIP_CONFIG)) {
A
Alex Ross 已提交
2921 2922
			const entry: any = <any>((await entries)[0]);
			if (entry.task) {
A
Alex Ross 已提交
2923
				this.handleSelection(entry);
A
Alex Ross 已提交
2924 2925
				return;
			}
2926 2927
		}

C
Christof Marti 已提交
2928
		this.quickInputService.pick(entries,
2929 2930 2931 2932 2933 2934
			{ placeHolder: nls.localize('TaskService.pickTask', 'Select a task to configure') }, cancellationToken).
			then(async (selection) => {
				if (cancellationToken.isCancellationRequested) {
					// canceled when there's only one task
					const task = (await entries)[0];
					if ((<any>task).task) {
A
Alex Ross 已提交
2935
						selection = <TaskQuickPickEntryType>task;
2936 2937
					}
				}
A
Alex Ross 已提交
2938
				this.handleSelection(selection);
D
Dirk Baeumer 已提交
2939
			});
2940 2941
	}

2942 2943 2944 2945
	private runConfigureDefaultBuildTask(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2946
		if (this.schemaVersion === JsonSchemaVersion.V2_0_0) {
2947 2948
			this.tasks().then((tasks => {
				if (tasks.length === 0) {
2949
					this.runConfigureTasks();
2950 2951
					return;
				}
2952
				let selectedTask: Task | undefined;
2953
				let selectedEntry: TaskQuickPickEntry;
2954
				for (let task of tasks) {
A
Alex Ross 已提交
2955
					if (task.configurationProperties.group === TaskGroup.Build && task.configurationProperties.groupType === GroupType.default) {
2956
						selectedTask = task;
2957 2958 2959
						break;
					}
				}
2960 2961
				if (selectedTask) {
					selectedEntry = {
A
Alex Ross 已提交
2962
						label: nls.localize('TaskService.defaultBuildTaskExists', '{0} is already marked as the default build task', selectedTask.getQualifiedLabel()),
2963
						task: selectedTask
2964
					};
2965
				}
D
Dirk Baeumer 已提交
2966 2967
				this.showIgnoredFoldersMessage().then(() => {
					this.showQuickPick(tasks,
2968
						nls.localize('TaskService.pickDefaultBuildTask', 'Select the task to be used as the default build task'), undefined, true, false, selectedEntry).
2969 2970
						then((entry) => {
							let task: Task | undefined | null = entry ? entry.task : undefined;
2971
							if ((task === undefined) || (task === null)) {
D
Dirk Baeumer 已提交
2972 2973
								return;
							}
2974
							if (task === selectedTask && CustomTask.is(task)) {
D
Dirk Baeumer 已提交
2975 2976 2977
								this.openConfig(task);
							}
							if (!InMemoryTask.is(task)) {
2978 2979
								this.customize(task, { group: { kind: 'build', isDefault: true } }, true).then(() => {
									if (selectedTask && (task !== selectedTask) && !InMemoryTask.is(selectedTask)) {
2980
										this.customize(selectedTask, { group: 'build' }, false);
2981 2982
									}
								});
D
Dirk Baeumer 已提交
2983 2984 2985
							}
						});
				});
2986 2987
			}));
		} else {
2988
			this.runConfigureTasks();
2989 2990 2991 2992 2993 2994 2995
		}
	}

	private runConfigureDefaultTestTask(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2996
		if (this.schemaVersion === JsonSchemaVersion.V2_0_0) {
2997 2998
			this.tasks().then((tasks => {
				if (tasks.length === 0) {
2999
					this.runConfigureTasks();
3000
					return;
3001
				}
3002
				let selectedTask: Task | undefined;
3003 3004
				let selectedEntry: TaskQuickPickEntry;

3005
				for (let task of tasks) {
A
Alex Ross 已提交
3006
					if (task.configurationProperties.group === TaskGroup.Test && task.configurationProperties.groupType === GroupType.default) {
3007
						selectedTask = task;
3008 3009 3010
						break;
					}
				}
3011 3012
				if (selectedTask) {
					selectedEntry = {
A
Alex Ross 已提交
3013
						label: nls.localize('TaskService.defaultTestTaskExists', '{0} is already marked as the default test task.', selectedTask.getQualifiedLabel()),
3014 3015
						task: selectedTask
					};
3016
				}
3017

D
Dirk Baeumer 已提交
3018
				this.showIgnoredFoldersMessage().then(() => {
3019
					this.showQuickPick(tasks,
3020 3021
						nls.localize('TaskService.pickDefaultTestTask', 'Select the task to be used as the default test task'), undefined, true, false, selectedEntry).then((entry) => {
							let task: Task | undefined | null = entry ? entry.task : undefined;
3022 3023 3024 3025 3026 3027 3028 3029 3030
							if (!task) {
								return;
							}
							if (task === selectedTask && CustomTask.is(task)) {
								this.openConfig(task);
							}
							if (!InMemoryTask.is(task)) {
								this.customize(task, { group: { kind: 'test', isDefault: true } }, true).then(() => {
									if (selectedTask && (task !== selectedTask) && !InMemoryTask.is(selectedTask)) {
3031
										this.customize(selectedTask, { group: 'test' }, false);
3032 3033 3034 3035
									}
								});
							}
						});
3036 3037 3038
				});
			}));
		} else {
3039
			this.runConfigureTasks();
3040 3041
		}
	}
3042

3043
	public async runShowTasks(): Promise<void> {
3044 3045 3046
		if (!this.canRunCommand()) {
			return;
		}
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
		const activeTasks: Task[] = await this.getActiveTasks();
		if (activeTasks.length === 1) {
			this._taskSystem!.revealTask(activeTasks[0]);
		} else {
			this.showQuickPick(this.getActiveTasks(),
				nls.localize('TaskService.pickShowTask', 'Select the task to show its output'),
				{
					label: nls.localize('TaskService.noTaskIsRunning', 'No task is running'),
					task: null
				},
				false, true
			).then((entry) => {
				let task: Task | undefined | null = entry ? entry.task : undefined;
				if (task === undefined || task === null) {
					return;
				}
				this._taskSystem!.revealTask(task);
			});
		}
3066
	}
3067
}