abstractTaskService.ts 114.6 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 { ValidationStatus, ValidationState } from 'vs/base/common/parsers';
19
import * as UUID from 'vs/base/common/uuid';
20
import * as Platform from 'vs/base/common/platform';
21
import { LRUCache, Touch } from 'vs/base/common/map';
22
import { IMarkerService } from 'vs/platform/markers/common/markers';
E
Erich Gamma 已提交
23
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
24
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
25
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
26
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
27
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
28
import { ProblemMatcherRegistry, NamedProblemMatcher } from 'vs/workbench/contrib/tasks/common/problemMatcher';
29
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
30
import { IProgressService, IProgressOptions, ProgressLocation } from 'vs/platform/progress/common/progress';
31

32
import { IOpenerService } from 'vs/platform/opener/common/opener';
33
import { IHostService } from 'vs/workbench/services/host/browser/host';
34
import { INotificationService } from 'vs/platform/notification/common/notification';
35
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
36

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

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

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

48
import { ITerminalService, ITerminalInstanceService } from 'vs/workbench/contrib/terminal/browser/terminal';
49

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

60
import * as TaskConfig from '../common/taskConfiguration';
61
import { TerminalTaskSystem } from './terminalTaskSystem';
62

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

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

69
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
70
import { IPathService } from 'vs/workbench/services/path/common/pathService';
71
import { format } from 'vs/base/common/jsonFormatter';
72
import { ITextModelService, IResolvedTextEditorModel } from 'vs/editor/common/services/resolverService';
73
import { applyEdits } from 'vs/base/common/jsonEdit';
A
Alex Ross 已提交
74
import { SaveReason } from 'vs/workbench/common/editor';
75
import { ITextEditorSelection, TextEditorSelectionRevealType } from 'vs/platform/editor/common/editor';
76
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
77
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
78
import { IViewsService, IViewDescriptorService } from 'vs/workbench/common/views';
M
Martin Aeschlimann 已提交
79
import { isWorkspaceFolder, TaskQuickPickEntry, QUICKOPEN_DETAIL_CONFIG, TaskQuickPick, QUICKOPEN_SKIP_CONFIG, configureTaskIcon } from 'vs/workbench/contrib/tasks/browser/taskQuickPick';
A
Alex Ross 已提交
80
import { ILogService } from 'vs/platform/log/common/log';
81
import { once } from 'vs/base/common/functional';
M
Martin Aeschlimann 已提交
82
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
83

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

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

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

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
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 已提交
128
export interface WorkspaceFolderConfigurationResult {
S
Sandeep Somavarapu 已提交
129
	workspaceFolder: IWorkspaceFolder;
130
	config: TaskConfig.ExternalTaskRunnerConfiguration | undefined;
131 132 133
	hasErrors: boolean;
}

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

138 139 140 141 142 143 144
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 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158
	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);
159 160
		if (!result) {
			result = [];
A
Alex Ross 已提交
161
			this._store.set(key, result);
162 163 164 165
		}
		return result;
	}

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

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

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

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

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

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

202 203
	private static nextHandle: number = 0;

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

A
Alex Ross 已提交
214
	protected _workspaceTasksPromise?: Promise<Map<string, WorkspaceFolderTaskResult>>;
215

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

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

A
Alex Ross 已提交
223 224
	protected _outputChannel: IOutputChannel;
	protected readonly _onDidStateChange: Emitter<TaskEvent>;
225 226
	private _waitForSupportedExecutions: Promise<void>;
	private _onDidRegisterSupportedExecutions: Emitter<void> = new Emitter();
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,
A
Alex Ross 已提交
240
		@IModelService protected readonly modelService: IModelService,
241 242
		@IExtensionService private readonly extensionService: IExtensionService,
		@IQuickInputService private readonly quickInputService: IQuickInputService,
A
Alex Ross 已提交
243
		@IConfigurationResolverService protected readonly configurationResolverService: IConfigurationResolverService,
244 245
		@ITerminalService private readonly terminalService: ITerminalService,
		@IStorageService private readonly storageService: IStorageService,
246
		@IProgressService private readonly progressService: IProgressService,
247
		@IOpenerService private readonly openerService: IOpenerService,
248
		@IHostService private readonly _hostService: IHostService,
249
		@IDialogService protected readonly dialogService: IDialogService,
250
		@INotificationService private readonly notificationService: INotificationService,
251
		@IContextKeyService protected readonly contextKeyService: IContextKeyService,
252
		@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
253
		@ITerminalInstanceService private readonly terminalInstanceService: ITerminalInstanceService,
254
		@IPathService private readonly pathService: IPathService,
255
		@ITextModelService private readonly textModelResolverService: ITextModelService,
256
		@IPreferencesService private readonly preferencesService: IPreferencesService,
A
Alex Ross 已提交
257 258
		@IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService,
		@ILogService private readonly logService: ILogService
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._onDidStateChange = this._register(new Emitter());
310
		this.registerCommands();
311 312 313 314 315 316 317 318 319 320 321 322 323
		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) {
324
				entry = await this.showQuickPick(tasks, nls.localize('TaskService.pickBuildTaskForLabel', 'Select the build task (there is no default build task defined)'));
325 326 327 328 329 330 331 332
			}

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

334 335 336
		this._waitForSupportedExecutions = new Promise(resolve => {
			once(this._onDidRegisterSupportedExecutions.event)(() => resolve());
		});
337 338
	}

339 340 341 342 343 344 345 346 347 348 349 350 351
	public registerSupportedExecutions(custom?: boolean, shell?: boolean, process?: boolean) {
		if (custom !== undefined) {
			const customContext = CustomExecutionSupportedContext.bindTo(this.contextKeyService);
			customContext.set(custom);
		}
		if (shell !== undefined) {
			const shellContext = ShellExecutionSupportedContext.bindTo(this.contextKeyService);
			shellContext.set(shell);
		}
		if (process !== undefined) {
			const processContext = ProcessExecutionSupportedContext.bindTo(this.contextKeyService);
			processContext.set(process);
		}
352
		this._onDidRegisterSupportedExecutions.fire();
353 354
	}

355 356 357 358
	public get onDidStateChange(): Event<TaskEvent> {
		return this._onDidStateChange.event;
	}

359 360 361 362
	public get supportsMultipleTaskExecutions(): boolean {
		return this.inTerminal();
	}

363
	private registerCommands(): void {
364 365 366 367 368 369 370 371 372 373 374 375 376 377
		CommandsRegistry.registerCommand({
			id: 'workbench.action.tasks.runTask',
			handler: (accessor, arg) => {
				this.runTaskCommand(arg);
			},
			description: {
				description: 'Run Task',
				args: [{
					name: 'args',
					schema: {
						'type': 'string',
					}
				}]
			}
378 379
		});

A
Alex Ross 已提交
380
		CommandsRegistry.registerCommand('workbench.action.tasks.reRunTask', (accessor, arg) => {
381
			this.reRunTaskCommand();
A
Alex Ross 已提交
382 383
		});

384
		CommandsRegistry.registerCommand('workbench.action.tasks.restartTask', (accessor, arg) => {
385
			this.runRestartTaskCommand(arg);
386 387
		});

388
		CommandsRegistry.registerCommand('workbench.action.tasks.terminate', (accessor, arg) => {
389
			this.runTerminateCommand(arg);
390 391 392 393 394 395 396 397 398 399 400 401 402
		});

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

		CommandsRegistry.registerCommand('workbench.action.tasks.build', () => {
			if (!this.canRunCommand()) {
				return;
			}
403
			this.runBuildCommand();
404 405 406 407 408
		});

		CommandsRegistry.registerCommand('workbench.action.tasks.test', () => {
			if (!this.canRunCommand()) {
				return;
409
			}
410
			this.runTestCommand();
411
		});
412

413 414 415 416
		CommandsRegistry.registerCommand('workbench.action.tasks.configureTaskRunner', () => {
			this.runConfigureTasks();
		});

417 418 419 420 421 422 423
		CommandsRegistry.registerCommand('workbench.action.tasks.configureDefaultBuildTask', () => {
			this.runConfigureDefaultBuildTask();
		});

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

425 426
		CommandsRegistry.registerCommand('workbench.action.tasks.showTasks', async () => {
			return this.runShowTasks();
427
		});
428

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

431
		CommandsRegistry.registerCommand('workbench.action.tasks.openUserTasks', async () => {
432 433
			const resource = this.getResourceForKind(TaskSourceKind.User);
			if (resource) {
434 435 436 437 438 439 440 441
				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);
442 443
			}
		});
E
Erich Gamma 已提交
444 445
	}

D
Dirk Baeumer 已提交
446
	private get workspaceFolders(): IWorkspaceFolder[] {
447
		if (!this._workspaceFolders) {
D
Dirk Baeumer 已提交
448 449
			this.updateSetup();
		}
450
		return this._workspaceFolders!;
D
Dirk Baeumer 已提交
451 452
	}

D
Dirk Baeumer 已提交
453
	private get ignoredWorkspaceFolders(): IWorkspaceFolder[] {
454
		if (!this._ignoredWorkspaceFolders) {
D
Dirk Baeumer 已提交
455 456
			this.updateSetup();
		}
457
		return this._ignoredWorkspaceFolders!;
D
Dirk Baeumer 已提交
458 459
	}

A
Alex Ross 已提交
460
	protected get executionEngine(): ExecutionEngine {
R
Rob Lourens 已提交
461
		if (this._executionEngine === undefined) {
D
Dirk Baeumer 已提交
462 463
			this.updateSetup();
		}
464
		return this._executionEngine!;
D
Dirk Baeumer 已提交
465 466 467
	}

	private get schemaVersion(): JsonSchemaVersion {
R
Rob Lourens 已提交
468
		if (this._schemaVersion === undefined) {
D
Dirk Baeumer 已提交
469 470
			this.updateSetup();
		}
471
		return this._schemaVersion!;
D
Dirk Baeumer 已提交
472 473
	}

D
Dirk Baeumer 已提交
474
	private get showIgnoreMessage(): boolean {
R
Rob Lourens 已提交
475
		if (this._showIgnoreMessage === undefined) {
A
Alex Ross 已提交
476
			this._showIgnoreMessage = !this.storageService.getBoolean(AbstractTaskService.IgnoreTask010DonotShowAgain_key, StorageScope.WORKSPACE, false);
D
Dirk Baeumer 已提交
477
		}
478
		return this._showIgnoreMessage;
D
Dirk Baeumer 已提交
479 480
	}

481
	private updateSetup(setup?: [IWorkspaceFolder[], IWorkspaceFolder[], ExecutionEngine, JsonSchemaVersion, IWorkspace | undefined]): void {
D
Dirk Baeumer 已提交
482 483 484
		if (!setup) {
			setup = this.computeWorkspaceFolderSetup();
		}
485 486 487 488
		this._workspaceFolders = setup[0];
		if (this._ignoredWorkspaceFolders) {
			if (this._ignoredWorkspaceFolders.length !== setup[1].length) {
				this._showIgnoreMessage = undefined;
D
Dirk Baeumer 已提交
489 490
			} else {
				let set: Set<string> = new Set();
491
				this._ignoredWorkspaceFolders.forEach(folder => set.add(folder.uri.toString()));
D
Dirk Baeumer 已提交
492 493
				for (let folder of setup[1]) {
					if (!set.has(folder.uri.toString())) {
494
						this._showIgnoreMessage = undefined;
D
Dirk Baeumer 已提交
495 496 497 498 499
						break;
					}
				}
			}
		}
500 501 502
		this._ignoredWorkspaceFolders = setup[1];
		this._executionEngine = setup[2];
		this._schemaVersion = setup[3];
503
		this._workspace = setup[4];
D
Dirk Baeumer 已提交
504 505
	}

A
Alex Ross 已提交
506
	protected showOutput(runSource: TaskRunSource = TaskRunSource.User): void {
A
Alex Ross 已提交
507
		if ((runSource === TaskRunSource.User) || (runSource === TaskRunSource.ConfigurationChange)) {
508 509 510 511 512 513 514
			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);
					}
				}]);
515
		}
516 517
	}

518
	protected disposeTaskSystemListeners(): void {
519 520 521
		if (this._taskSystemListener) {
			this._taskSystemListener.dispose();
		}
E
Erich Gamma 已提交
522 523
	}

524
	public registerTaskProvider(provider: ITaskProvider, type: string): IDisposable {
525
		if (!provider) {
526 527 528
			return {
				dispose: () => { }
			};
529
		}
A
Alex Ross 已提交
530
		let handle = AbstractTaskService.nextHandle++;
531
		this._providers.set(handle, provider);
532
		this._providerTypes.set(handle, type);
533 534 535
		return {
			dispose: () => {
				this._providers.delete(handle);
536
				this._providerTypes.delete(handle);
537 538
			}
		};
539 540
	}

541
	public registerTaskSystem(key: string, info: TaskSystemInfo): void {
542 543 544 545 546 547 548 549 550 551
		if (!this._taskSystemInfos.has(key) || info.platform !== Platform.Platform.Web) {
			this._taskSystemInfos.set(key, info);
		}
	}

	private getTaskSystemInfo(key: string): TaskSystemInfo | undefined {
		if (this.environmentService.remoteAuthority) {
			return this._taskSystemInfos.get(key);
		}
		return undefined;
552 553
	}

G
Gabriel DeBacker 已提交
554
	public extensionCallbackTaskComplete(task: Task, result: number): Promise<void> {
555 556 557
		if (!this._taskSystem) {
			return Promise.resolve();
		}
G
Gabriel DeBacker 已提交
558
		return this._taskSystem.customExecutionComplete(task, result);
559 560
	}

A
Alex Ross 已提交
561 562
	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 已提交
563
		if (this.ignoredWorkspaceFolders.some(ignored => ignored.name === name)) {
564
			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 已提交
565
		}
566 567 568 569
		const key: string | KeyedTaskIdentifier | undefined = !Types.isString(identifier)
			? TaskDefinition.createTaskIdentifier(identifier, console)
			: identifier;

R
Rob Lourens 已提交
570
		if (key === undefined) {
571
			return Promise.resolve(undefined);
572
		}
573
		return this.getGroupedTasks().then((map) => {
A
Alex Ross 已提交
574
			let values = map.get(folder);
575
			values = values.concat(map.get(USER_TASKS_GROUP_KEY));
A
Alex Ross 已提交
576

577 578 579
			if (!values) {
				return undefined;
			}
580 581
			values = values.filter(task => task.matches(key, compareId)).sort(task => task._source.kind === TaskSourceKind.Extension ? 1 : -1);
			return values.length > 0 ? values[0] : undefined;
582 583 584
		});
	}

A
Alex Ross 已提交
585
	public async tryResolveTask(configuringTask: ConfiguringTask): Promise<Task | undefined> {
586
		await Promise.all([this.extensionService.activateByEvent('onCommand:workbench.action.tasks.runTask'), this.extensionService.whenInstalledExtensionsRegistered()]);
A
Alex Ross 已提交
587
		let matchingProvider: ITaskProvider | undefined;
588
		let matchingProviderUnavailable: boolean = false;
A
Alex Ross 已提交
589
		for (const [handle, provider] of this._providers) {
590 591 592 593 594 595
			const providerType = this._providerTypes.get(handle);
			if (configuringTask.type === providerType) {
				if (providerType && !this.isTaskProviderEnabled(providerType)) {
					matchingProviderUnavailable = true;
					continue;
				}
A
Alex Ross 已提交
596 597 598 599
				matchingProvider = provider;
				break;
			}
		}
600

A
Alex Ross 已提交
601
		if (!matchingProvider) {
602 603 604 605 606 607 608
			if (matchingProviderUnavailable) {
				this._outputChannel.append(nls.localize(
					'TaskService.providerUnavailable',
					'Warning: {0} tasks are unavailable in the current environment.\n',
					configuringTask.configures.type
				));
			}
A
Alex Ross 已提交
609
			return;
610
		}
A
Alex Ross 已提交
611 612 613 614 615 616

		// Try to resolve the task first
		try {
			const resolvedTask = await matchingProvider.resolveTask(configuringTask);
			if (resolvedTask && (resolvedTask._id === configuringTask._id)) {
				return TaskConfig.createCustomTask(resolvedTask, configuringTask);
617
			}
A
Alex Ross 已提交
618 619 620 621 622 623 624 625 626 627 628 629 630
		} 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;
631 632
	}

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

A
Alex Ross 已提交
635 636
	public tasks(filter?: TaskFilter): Promise<Task[]> {
		if (!this.versionAndEngineCompatible(filter)) {
637
			return Promise.resolve<Task[]>([]);
638
		}
639
		return this.getGroupedTasks(filter ? filter.type : undefined).then((map) => {
640 641 642 643 644 645
			if (!filter || !filter.type) {
				return map.all();
			}
			let result: Task[] = [];
			map.forEach((tasks) => {
				for (let task of tasks) {
646
					if (ContributedTask.is(task) && ((task.defines.type === filter.type) || (task._source.label === filter.type))) {
647
						result.push(task);
648 649 650 651
					} else if (CustomTask.is(task)) {
						if (task.type === filter.type) {
							result.push(task);
						} else {
A
Alex Ross 已提交
652
							let customizes = task.customizes();
653 654 655 656
							if (customizes && customizes.type === filter.type) {
								result.push(task);
							}
						}
657 658 659 660 661
					}
				}
			});
			return result;
		});
662
	}
663

A
Alex Ross 已提交
664 665 666 667 668
	public taskTypes(): string[] {
		const types: string[] = [];
		if (this.isProvideTasksEnabled()) {
			for (const [handle] of this._providers) {
				const type = this._providerTypes.get(handle);
669
				if (type && this.isTaskProviderEnabled(type)) {
A
Alex Ross 已提交
670 671 672 673 674 675 676
					types.push(type);
				}
			}
		}
		return types;
	}

677 678 679 680
	public createSorter(): TaskSorter {
		return new TaskSorter(this.contextService.getWorkspace() ? this.contextService.getWorkspace().folders : []);
	}

J
Johannes Rieken 已提交
681
	public isActive(): Promise<boolean> {
682
		if (!this._taskSystem) {
683
			return Promise.resolve(false);
684 685 686 687
		}
		return this._taskSystem.isActive();
	}

J
Johannes Rieken 已提交
688
	public getActiveTasks(): Promise<Task[]> {
689
		if (!this._taskSystem) {
690
			return Promise.resolve([]);
691
		}
692
		return Promise.resolve(this._taskSystem.getActiveTasks());
693 694
	}

695 696 697 698 699 700 701
	public getBusyTasks(): Promise<Task[]> {
		if (!this._taskSystem) {
			return Promise.resolve([]);
		}
		return Promise.resolve(this._taskSystem.getBusyTasks());
	}

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
	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;
	}

725
	public getRecentlyUsedTasks(): LRUCache<string, string> {
726 727 728
		if (this._recentlyUsedTasks) {
			return this._recentlyUsedTasks;
		}
729 730 731
		const quickOpenHistoryLimit = this.configurationService.getValue<number>(QUICKOPEN_HISTORY_LIMIT_CONFIG);
		this._recentlyUsedTasks = new LRUCache<string, string>(quickOpenHistoryLimit);

732
		let storageValue = this.storageService.get(AbstractTaskService.RecentlyUsedTasks_KeyV2, StorageScope.WORKSPACE);
733 734
		if (storageValue) {
			try {
735
				let values: [string, string][] = JSON.parse(storageValue);
736 737
				if (Array.isArray(values)) {
					for (let value of values) {
738
						this._recentlyUsedTasks.set(value[0], value[1]);
739 740 741 742 743 744 745 746 747
					}
				}
			} catch (error) {
				// Ignore. We use the empty result
			}
		}
		return this._recentlyUsedTasks;
	}

A
Alex Ross 已提交
748 749 750 751 752 753 754 755 756 757
	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;
		});
758
		const folderToTasksMap: Map<string, any> = new Map();
A
Alex Ross 已提交
759 760
		const recentlyUsedTasks = this.getRecentlyUsedTasks();
		const tasks: (Task | ConfiguringTask)[] = [];
761 762
		for (const entry of recentlyUsedTasks.entries()) {
			const key = entry[0];
A
Alex Ross 已提交
763
			const task = JSON.parse(entry[1]);
A
Alex Ross 已提交
764
			const folder = this.getFolderFromTaskKey(key);
765 766 767
			if (folder && !folderToTasksMap.has(folder)) {
				folderToTasksMap.set(folder, []);
			}
A
Alex Ross 已提交
768
			if (folder && (folderMap[folder] || (folder === USER_TASKS_GROUP_KEY)) && task) {
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
				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 已提交
784
				}
785 786 787 788 789 790 791 792
			});
			for (const configuration in customized) {
				const taskKey = customized[configuration].getRecentlyUsedKey();
				if (taskKey) {
					readTasksMap.set(taskKey, customized[configuration]);
				}
			}
		}
A
Alex Ross 已提交
793

794 795 796
		for (const key of recentlyUsedTasks.keys()) {
			if (readTasksMap.has(key)) {
				tasks.push(readTasksMap.get(key)!);
A
Alex Ross 已提交
797 798 799 800 801
			}
		}
		return tasks;
	}

802 803 804 805 806 807 808
	public removeRecentlyUsedTask(taskRecentlyUsedKey: string) {
		if (this.getRecentlyUsedTasks().has(taskRecentlyUsedKey)) {
			this.getRecentlyUsedTasks().delete(taskRecentlyUsedKey);
			this.saveRecentlyUsedTasks();
		}
	}

809 810 811 812 813 814 815
	private setTaskLRUCacheLimit() {
		const quickOpenHistoryLimit = this.configurationService.getValue<number>(QUICKOPEN_HISTORY_LIMIT_CONFIG);
		if (this._recentlyUsedTasks) {
			this._recentlyUsedTasks.limit = quickOpenHistoryLimit;
		}
	}

816 817
	private async setRecentlyUsedTask(task: Task): Promise<void> {
		let key = task.getRecentlyUsedKey();
818
		if (!InMemoryTask.is(task) && key) {
819 820 821 822 823 824 825 826 827 828 829 830 831
			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));
832 833
			this.saveRecentlyUsedTasks();
		}
834 835 836
	}

	private saveRecentlyUsedTasks(): void {
837
		if (!this._recentlyUsedTasks) {
838 839
			return;
		}
840 841 842 843 844
		const quickOpenHistoryLimit = this.configurationService.getValue<number>(QUICKOPEN_HISTORY_LIMIT_CONFIG);
		// setting history limit to 0 means no LRU sorting
		if (quickOpenHistoryLimit === 0) {
			return;
		}
845
		let keys = [...this._recentlyUsedTasks.keys()];
A
Alex Ross 已提交
846 847 848 849 850
		if (keys.length > quickOpenHistoryLimit) {
			keys = keys.slice(0, quickOpenHistoryLimit);
		}
		const keyValues: [string, string][] = [];
		for (const key of keys) {
851
			keyValues.push([key, this._recentlyUsedTasks.get(key, Touch.None)!]);
852
		}
853
		this.storageService.store(AbstractTaskService.RecentlyUsedTasks_KeyV2, JSON.stringify(keyValues), StorageScope.WORKSPACE, StorageTarget.USER);
854
	}
855

856
	private openDocumentation(): void {
857 858 859
		this.openerService.open(URI.parse('https://go.microsoft.com/fwlink/?LinkId=733558'));
	}

860
	public async build(): Promise<ITaskSummary> {
861
		return this.getGroupedTasks().then((tasks) => {
D
Dirk Baeumer 已提交
862
			let runnable = this.createRunnableTask(tasks, TaskGroup.Build);
863
			if (!runnable || !runnable.task) {
D
Dirk Baeumer 已提交
864
				if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
865 866 867 868
					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);
				}
869
			}
A
Alex Ross 已提交
870
			return this.executeTask(runnable.task, runnable.resolver, TaskRunSource.User);
871 872
		}).then(value => value, (error) => {
			this.handleError(error);
873
			return Promise.reject(error);
874 875 876
		});
	}

J
Johannes Rieken 已提交
877
	public runTest(): Promise<ITaskSummary> {
878
		return this.getGroupedTasks().then((tasks) => {
D
Dirk Baeumer 已提交
879
			let runnable = this.createRunnableTask(tasks, TaskGroup.Test);
880
			if (!runnable || !runnable.task) {
D
Dirk Baeumer 已提交
881
				if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
882 883 884 885
					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);
				}
886
			}
A
Alex Ross 已提交
887
			return this.executeTask(runnable.task, runnable.resolver, TaskRunSource.User);
888 889
		}).then(value => value, (error) => {
			this.handleError(error);
890
			return Promise.reject(error);
891 892 893
		});
	}

A
Alex Ross 已提交
894
	public run(task: Task | undefined, options?: ProblemMatcherRunOptions, runSource: TaskRunSource = TaskRunSource.System): Promise<ITaskSummary | undefined> {
895 896 897
		if (!task) {
			throw new TaskError(Severity.Info, nls.localize('TaskServer.noTask', 'Task to execute is undefined'), TaskErrors.TaskNotFound);
		}
A
Alex Ross 已提交
898 899 900

		return new Promise<ITaskSummary | undefined>(async (resolve) => {
			let resolver = this.createResolver();
901
			if (options && options.attachProblemMatcher && this.shouldAttachProblemMatcher(task) && !InMemoryTask.is(task)) {
A
Alex Ross 已提交
902 903
				const toExecute = await this.attachProblemMatcher(task);
				if (toExecute) {
A
Alex Ross 已提交
904
					resolve(this.executeTask(toExecute, resolver, runSource));
A
Alex Ross 已提交
905 906 907
				} else {
					resolve(undefined);
				}
A
Alex Ross 已提交
908
			} else {
909
				resolve(this.executeTask(task, resolver, runSource));
910
			}
911 912 913 914 915 916 917 918
		}).then((value) => {
			if (runSource === TaskRunSource.User) {
				this.getWorkspaceTasks().then(workspaceTasks => {
					RunAutomaticTasks.promptForPermission(this, this.storageService, this.notificationService, workspaceTasks);
				});
			}
			return value;
		}, (error) => {
919
			this.handleError(error);
920
			return Promise.reject(error);
921 922 923
		});
	}

924 925
	private isProvideTasksEnabled(): boolean {
		const settingValue = this.configurationService.getValue('task.autoDetect');
926
		return settingValue === 'on';
927 928
	}

929
	private isProblemMatcherPromptEnabled(type?: string): boolean {
930
		const settingValue = this.configurationService.getValue(PROBLEM_MATCHER_NEVER_CONFIG);
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
		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) {
955 956
			return false;
		}
D
Dirk Baeumer 已提交
957
		if (!this.canCustomize(task)) {
958 959
			return false;
		}
R
Rob Lourens 已提交
960
		if (task.configurationProperties.group !== undefined && task.configurationProperties.group !== TaskGroup.Build) {
961 962
			return false;
		}
R
Rob Lourens 已提交
963
		if (task.configurationProperties.problemMatchers !== undefined && task.configurationProperties.problemMatchers.length > 0) {
964 965
			return false;
		}
966
		if (ContributedTask.is(task)) {
967
			return !task.hasDefinedMatchers && !!task.configurationProperties.problemMatchers && (task.configurationProperties.problemMatchers.length === 0);
968
		}
969 970
		if (CustomTask.is(task)) {
			let configProperties: TaskConfig.ConfigurationProperties = task._source.config.element;
971
			return configProperties.problemMatcher === undefined && !task.hasDefinedMatchers;
972 973
		}
		return false;
974 975
	}

976 977 978 979 980 981
	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;
		}
982 983 984 985 986
		let newValue: IStringDictionary<boolean>;
		if (current !== false) {
			newValue = <any>current;
		} else {
			newValue = Object.create(null);
987
		}
988
		newValue[type] = true;
989
		return this.configurationService.updateValue(PROBLEM_MATCHER_NEVER_CONFIG, newValue);
990 991
	}

992
	private attachProblemMatcher(task: ContributedTask | CustomTask): Promise<Task | undefined> {
C
Christof Marti 已提交
993
		interface ProblemMatcherPickEntry extends IQuickPickItem {
994
			matcher: NamedProblemMatcher | undefined;
995
			never?: boolean;
996
			learnMore?: boolean;
997
			setting?: string;
998
		}
C
Christof Marti 已提交
999
		let entries: QuickPickInput<ProblemMatcherPickEntry>[] = [];
1000 1001
		for (let key of ProblemMatcherRegistry.keys()) {
			let matcher = ProblemMatcherRegistry.get(key);
1002 1003 1004
			if (matcher.deprecated) {
				continue;
			}
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
			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) {
1016 1017 1018 1019 1020 1021 1022
			entries = entries.sort((a, b) => {
				if (a.label && b.label) {
					return a.label.localeCompare(b.label);
				} else {
					return 0;
				}
			});
C
Christof Marti 已提交
1023
			entries.unshift({ type: 'separator', label: nls.localize('TaskService.associate', 'associate') });
1024 1025 1026 1027 1028 1029 1030
			let taskType: string;
			if (CustomTask.is(task)) {
				let configProperties: TaskConfig.ConfigurationProperties = task._source.config.element;
				taskType = (<any>configProperties).type;
			} else {
				taskType = task.getDefinition().type;
			}
1031
			entries.unshift(
1032
				{ label: nls.localize('TaskService.attachProblemMatcher.continueWithout', 'Continue without scanning the task output'), matcher: undefined },
1033 1034
				{ 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 },
1035
				{ label: nls.localize('TaskService.attachProblemMatcher.learnMoreAbout', 'Learn more about scanning the task output'), matcher: undefined, learnMore: true }
1036
			);
C
Christof Marti 已提交
1037
			return this.quickInputService.pick(entries, {
1038
				placeHolder: nls.localize('selectProblemMatcher', 'Select for which kind of errors and warnings to scan the task output'),
1039
			}).then(async (selected) => {
1040 1041 1042 1043
				if (selected) {
					if (selected.learnMore) {
						this.openDocumentation();
						return undefined;
1044 1045 1046
					} else if (selected.never) {
						this.customize(task, { problemMatcher: [] }, true);
						return task;
1047
					} else if (selected.matcher) {
A
Alex Ross 已提交
1048
						let newTask = task.clone();
1049
						let matcherReference = `$${selected.matcher.name}`;
1050
						let properties: CustomizationProperties = { problemMatcher: [matcherReference] };
A
Alex Ross 已提交
1051
						newTask.configurationProperties.problemMatchers = [matcherReference];
1052
						let matcher = ProblemMatcherRegistry.get(selected.matcher.name);
R
Rob Lourens 已提交
1053
						if (matcher && matcher.watching !== undefined) {
1054
							properties.isBackground = true;
A
Alex Ross 已提交
1055
							newTask.configurationProperties.isBackground = true;
1056 1057
						}
						this.customize(task, properties, true);
1058
						return newTask;
1059 1060 1061
					} else if (selected.setting) {
						await this.updateNeverProblemMatcherSetting(selected.setting);
						return task;
1062 1063 1064 1065
					} else {
						return task;
					}
				} else {
1066
					return undefined;
1067 1068 1069
				}
			});
		}
1070
		return Promise.resolve(task);
1071 1072
	}

J
Johannes Rieken 已提交
1073
	public getTasksForGroup(group: string): Promise<Task[]> {
1074
		return this.getGroupedTasks().then((groups) => {
1075
			let result: Task[] = [];
1076 1077
			groups.forEach((tasks) => {
				for (let task of tasks) {
A
Alex Ross 已提交
1078
					if (task.configurationProperties.group === group) {
1079 1080
						result.push(task);
					}
1081
				}
1082
			});
1083 1084 1085 1086
			return result;
		});
	}

1087 1088
	public needsFolderQualification(): boolean {
		return this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE;
D
Dirk Baeumer 已提交
1089 1090 1091
	}

	public canCustomize(task: Task): boolean {
D
Dirk Baeumer 已提交
1092
		if (this.schemaVersion !== JsonSchemaVersion.V2_0_0) {
D
Dirk Baeumer 已提交
1093 1094 1095 1096 1097 1098
			return false;
		}
		if (CustomTask.is(task)) {
			return true;
		}
		if (ContributedTask.is(task)) {
A
Alex Ross 已提交
1099
			return !!task.getWorkspaceFolder();
D
Dirk Baeumer 已提交
1100 1101
		}
		return false;
1102 1103
	}

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
	private async formatTaskForJson(resource: URI, task: TaskConfig.CustomTask | TaskConfig.ConfiguringTask): Promise<string> {
		let reference: IReference<IResolvedTextEditorModel> | undefined;
		let stringValue: string = '';
		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);
1114 1115 1116
			const regex = new RegExp(eol + (insertSpaces ? ' '.repeat(tabSize) : '\\t'), 'g');
			stringified = stringified.replace(regex, eol + (insertSpaces ? ' '.repeat(tabSize * 3) : '\t\t\t'));
			const twoTabs = insertSpaces ? ' '.repeat(tabSize * 2) : '\t\t';
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
			stringValue = twoTabs + stringified.slice(0, stringified.length - 1) + twoTabs + stringified.slice(stringified.length - 1);
		} finally {
			if (reference) {
				reference.dispose();
			}
		}
		return stringValue;
	}

	private openEditorAtTask(resource: URI | undefined, task: TaskConfig.CustomTask | TaskConfig.ConfiguringTask | string | undefined, configIndex: number = -1): Promise<boolean> {
1127
		if (resource === undefined) {
A
Alex Ross 已提交
1128
			return Promise.resolve(false);
1129 1130 1131 1132
		}
		let selection: ITextEditorSelection | undefined;
		return this.fileService.readFile(resource).then(content => content.value).then(async content => {
			if (!content) {
A
Alex Ross 已提交
1133
				return false;
1134 1135 1136
			}
			if (task) {
				const contentValue = content.toString();
1137 1138
				let stringValue: string | undefined;
				if (configIndex !== -1) {
A
Alex Ross 已提交
1139
					const json: TaskConfig.ExternalTaskRunnerConfiguration = this.configurationService.getValue<TaskConfig.ExternalTaskRunnerConfiguration>('tasks', { resource });
1140 1141 1142 1143 1144 1145 1146 1147 1148
					if (json.tasks && (json.tasks.length > configIndex)) {
						stringValue = await this.formatTaskForJson(resource, json.tasks[configIndex]);
					}
				}
				if (!stringValue) {
					if (typeof task === 'string') {
						stringValue = task;
					} else {
						stringValue = await this.formatTaskForJson(resource, task);
1149
					}
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
				}

				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,
1174
					selectionRevealType: TextEditorSelectionRevealType.CenterIfOutsideViewport
1175
				}
A
Alex Ross 已提交
1176
			}).then(() => !!selection);
1177 1178 1179
		});
	}

A
Alex Ross 已提交
1180
	private createCustomizableTask(task: ContributedTask | CustomTask | ConfiguringTask): TaskConfig.CustomTask | TaskConfig.ConfiguringTask | undefined {
1181
		let toCustomize: TaskConfig.CustomTask | TaskConfig.ConfiguringTask | undefined;
A
Alex Ross 已提交
1182
		let taskConfig = CustomTask.is(task) || ConfiguringTask.is(task) ? task._source.config : undefined;
1183
		if (taskConfig && taskConfig.element) {
1184
			toCustomize = { ...(taskConfig.element) };
1185 1186 1187
		} else if (ContributedTask.is(task)) {
			toCustomize = {
			};
1188
			let identifier: TaskConfig.TaskIdentifier = Object.assign(Object.create(null), task.defines);
1189
			delete identifier['_key'];
1190
			Object.keys(identifier).forEach(key => (<any>toCustomize)![key] = identifier[key]);
A
Alex Ross 已提交
1191 1192
			if (task.configurationProperties.problemMatchers && task.configurationProperties.problemMatchers.length > 0 && Types.isStringArray(task.configurationProperties.problemMatchers)) {
				toCustomize.problemMatcher = task.configurationProperties.problemMatchers;
1193
			}
A
Alex Ross 已提交
1194 1195 1196
			if (task.configurationProperties.group) {
				toCustomize.group = task.configurationProperties.group;
			}
1197 1198
		}
		if (!toCustomize) {
1199 1200 1201 1202 1203
			return undefined;
		}
		if (toCustomize.problemMatcher === undefined && task.configurationProperties.problemMatchers === undefined || (task.configurationProperties.problemMatchers && task.configurationProperties.problemMatchers.length === 0)) {
			toCustomize.problemMatcher = [];
		}
A
Alex Ross 已提交
1204 1205 1206 1207 1208 1209
		if (task._source.label !== 'Workspace') {
			toCustomize.label = task.configurationProperties.identifier;
		} else {
			toCustomize.label = task._label;
		}
		toCustomize.detail = task.configurationProperties.detail;
1210 1211 1212
		return toCustomize;
	}

A
Alex Ross 已提交
1213
	public customize(task: ContributedTask | CustomTask | ConfiguringTask, properties?: CustomizationProperties, openConfig?: boolean): Promise<void> {
1214 1215
		const workspaceFolder = task.getWorkspaceFolder();
		if (!workspaceFolder) {
1216
			return Promise.resolve(undefined);
1217
		}
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
		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;
1230 1231
		if (properties) {
			for (let property of Object.getOwnPropertyNames(properties)) {
1232
				let value = (<any>properties)[property];
R
Rob Lourens 已提交
1233
				if (value !== undefined && value !== null) {
1234
					(<any>toCustomize)[property] = value;
1235 1236
				}
			}
1237
		}
1238

1239
		let promise: Promise<void> | undefined;
D
Dirk Baeumer 已提交
1240
		if (!fileConfig) {
1241
			let value = {
D
Dirk Baeumer 已提交
1242
				version: '2.0.0',
1243
				tasks: [toCustomize]
D
Dirk Baeumer 已提交
1244
			};
1245 1246
			let content = [
				'{',
1247
				nls.localize('tasksJsonComment', '\t// See https://go.microsoft.com/fwlink/?LinkId=733558 \n\t// for the documentation about the tasks.json format'),
1248
			].join('\n') + JSON.stringify(value, null, '\t').substr(1);
1249
			let editorConfig = this.configurationService.getValue<any>();
1250
			if (editorConfig.editor.insertSpaces) {
1251
				content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + ' '.repeat(s2.length * editorConfig.editor.tabSize));
1252
			}
1253
			promise = this.textFileService.create(workspaceFolder.toResource('.vscode/tasks.json'), content).then(() => { });
D
Dirk Baeumer 已提交
1254
		} else {
1255
			// We have a global task configuration
1256
			if ((index === -1) && properties) {
R
Rob Lourens 已提交
1257
				if (properties.problemMatcher !== undefined) {
1258
					fileConfig.problemMatcher = properties.problemMatcher;
1259
					promise = this.writeConfiguration(workspaceFolder, 'tasks.problemMatchers', fileConfig.problemMatcher, task._source.kind);
R
Rob Lourens 已提交
1260
				} else if (properties.group !== undefined) {
1261
					fileConfig.group = properties.group;
1262
					promise = this.writeConfiguration(workspaceFolder, 'tasks.group', fileConfig.group, task._source.kind);
1263
				}
1264 1265 1266 1267
			} else {
				if (!Array.isArray(fileConfig.tasks)) {
					fileConfig.tasks = [];
				}
R
Rob Lourens 已提交
1268
				if (index === undefined) {
1269 1270 1271 1272
					fileConfig.tasks.push(toCustomize);
				} else {
					fileConfig.tasks[index] = toCustomize;
				}
1273
				promise = this.writeConfiguration(workspaceFolder, 'tasks.tasks', fileConfig.tasks, task._source.kind);
D
Dirk Baeumer 已提交
1274
			}
1275
		}
1276
		if (!promise) {
1277
			return Promise.resolve(undefined);
1278
		}
1279
		return promise.then(() => {
1280
			let event: TaskCustomizationTelemetryEvent = {
1281 1282
				properties: properties ? Object.getOwnPropertyNames(properties) : []
			};
K
kieferrm 已提交
1283
			/* __GDPR__
K
kieferrm 已提交
1284 1285 1286 1287
				"taskService.customize" : {
					"properties" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
				}
			*/
A
Alex Ross 已提交
1288
			this.telemetryService.publicLog(AbstractTaskService.CustomizationTelemetryEventName, event);
D
Dirk Baeumer 已提交
1289
			if (openConfig) {
1290
				this.openEditorAtTask(this.getResourceForTask(task), toCustomize);
D
Dirk Baeumer 已提交
1291 1292 1293 1294
			}
		});
	}

1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
	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 已提交
1308 1309 1310 1311 1312
		} else {
			return undefined;
		}
	}

1313
	private getResourceForKind(kind: string): URI | undefined {
1314
		this.updateSetup();
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
		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;
			}
		}
	}

1330
	private getResourceForTask(task: CustomTask | ConfiguringTask | ContributedTask): URI {
1331 1332 1333 1334 1335 1336 1337 1338 1339
		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 已提交
1340
			}
1341 1342 1343
			return uri;
		} else {
			return task.getWorkspaceFolder()!.toResource('.vscode/tasks.json');
1344 1345 1346
		}
	}

1347
	public async openConfig(task: CustomTask | ConfiguringTask | undefined): Promise<boolean> {
1348
		let resource: URI | undefined;
1349
		if (task) {
1350
			resource = this.getResourceForTask(task);
1351 1352 1353
		} else {
			resource = (this._workspaceFolders && (this._workspaceFolders.length > 0)) ? this._workspaceFolders[0].toResource('.vscode/tasks.json') : undefined;
		}
1354
		return this.openEditorAtTask(resource, task ? task._label : undefined, task ? task._source.config.index : -1);
1355 1356
	}

1357
	private createRunnableTask(tasks: TaskMap, group: TaskGroup): { task: Task; resolver: ITaskResolver } | undefined {
1358 1359 1360 1361 1362
		interface ResolverData {
			id: Map<string, Task>;
			label: Map<string, Task>;
			identifier: Map<string, Task>;
		}
1363

1364
		let resolverData: Map<string, ResolverData> = new Map();
1365 1366
		let workspaceTasks: Task[] = [];
		let extensionTasks: Task[] = [];
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
		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);
1380 1381 1382
				if (task.configurationProperties.identifier) {
					data.identifier.set(task.configurationProperties.identifier, task);
				}
A
Alex Ross 已提交
1383
				if (group && task.configurationProperties.group === group) {
1384 1385 1386 1387 1388
					if (task._source.kind === TaskSourceKind.Workspace) {
						workspaceTasks.push(task);
					} else {
						extensionTasks.push(task);
					}
1389
				}
D
Dirk Baeumer 已提交
1390
			}
1391 1392
		});
		let resolver: ITaskResolver = {
A
Alex Ross 已提交
1393
			resolve: async (uri: URI | string, alias: string) => {
1394
				let data = resolverData.get(typeof uri === 'string' ? uri : uri.toString());
1395 1396 1397 1398
				if (!data) {
					return undefined;
				}
				return data.id.get(alias) || data.label.get(alias) || data.identifier.get(alias);
1399 1400
			}
		};
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
		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;
		}

1411 1412
		// We can only have extension tasks if we are in version 2.0.0. Then we can even run
		// multiple build tasks.
1413 1414
		if (extensionTasks.length === 1) {
			return { task: extensionTasks[0], resolver };
1415 1416
		} else {
			let id: string = UUID.generateUuid();
A
Alex Ross 已提交
1417 1418 1419 1420 1421 1422 1423 1424
			let task: InMemoryTask = new InMemoryTask(
				id,
				{ kind: TaskSourceKind.InMemory, label: 'inMemory' },
				id,
				'inMemory',
				{ reevaluateOnRerun: true },
				{
					identifier: id,
1425
					dependsOn: extensionTasks.map((extensionTask) => { return { uri: extensionTask.getWorkspaceFolder()!.uri, task: extensionTask._id }; }),
A
Alex Ross 已提交
1426 1427 1428
					name: id,
				}
			);
1429
			return { task, resolver };
E
Erich Gamma 已提交
1430 1431 1432
		}
	}

A
Alex Ross 已提交
1433
	private createResolver(grouped?: TaskMap): ITaskResolver {
1434 1435 1436
		interface ResolverData {
			label: Map<string, Task>;
			identifier: Map<string, Task>;
1437
			taskIdentifier: Map<string, Task>;
1438
		}
1439

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

1442
		return {
A
Alex Ross 已提交
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
			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);
							}
						}
					});
				}
1464
				let data = resolverData.get(typeof uri === 'string' ? uri : uri.toString());
1465
				if (!data || !identifier) {
1466 1467
					return undefined;
				}
1468 1469 1470 1471
				if (Types.isString(identifier)) {
					return data.label.get(identifier) || data.identifier.get(identifier);
				} else {
					let key = TaskDefinition.createTaskIdentifier(identifier, console);
R
Rob Lourens 已提交
1472
					return key !== undefined ? data.taskIdentifier.get(key._key) : undefined;
1473
				}
1474
			}
1475 1476 1477
		};
	}

A
Alex Ross 已提交
1478
	private executeTask(task: Task, resolver: ITaskResolver, runSource: TaskRunSource): Promise<ITaskSummary> {
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
		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(() => {
1489
				let executeResult = this.getTaskSystem().run(task, resolver);
1490
				return this.handleExecuteResult(executeResult, runSource);
1491
			});
1492 1493 1494
		};

		const saveAllEditorsAndExecTask = async (task: Task, resolver: ITaskResolver): Promise<ITaskSummary> => {
1495
			return this.editorService.saveAll({ reason: SaveReason.AUTO }).then(() => {
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
				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);
		}
1525 1526
	}

1527
	private async handleExecuteResult(executeResult: ITaskExecuteResult, runSource?: TaskRunSource): Promise<ITaskSummary> {
1528 1529 1530 1531 1532 1533 1534
		if (executeResult.task.taskLoadMessages && executeResult.task.taskLoadMessages.length > 0) {
			executeResult.task.taskLoadMessages.forEach(loadMessage => {
				this._outputChannel.append(loadMessage + '\n');
			});
			this.showOutput();
		}

1535 1536 1537
		if (runSource === TaskRunSource.User) {
			await this.setRecentlyUsedTask(executeResult.task);
		}
A
Alex Ross 已提交
1538 1539
		if (executeResult.kind === TaskExecuteKind.Active) {
			let active = executeResult.active;
1540
			if (active && active.same) {
1541 1542
				if (this._taskSystem?.isTaskVisible(executeResult.task)) {
					const message = nls.localize('TaskSystem.activeSame.noBackground', 'The task \'{0}\' is already active.', executeResult.task.getQualifiedLabel());
1543
					let lastInstance = this.getTaskSystem().getLastInstance(executeResult.task) ?? executeResult.task;
1544
					this.notificationService.prompt(Severity.Warning, message,
1545 1546
						[{
							label: nls.localize('terminateTask', "Terminate Task"),
1547
							run: () => this.terminate(lastInstance)
1548 1549 1550
						},
						{
							label: nls.localize('restartTask', "Restart Task"),
1551
							run: () => this.restart(lastInstance)
1552 1553 1554
						}],
						{ sticky: true }
					);
A
Alex Ross 已提交
1555
				} else {
1556
					this._taskSystem?.revealTask(executeResult.task);
A
Alex Ross 已提交
1557 1558 1559 1560 1561 1562 1563 1564
				}
			} 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;
	}

1565
	public restart(task: Task): void {
1566 1567 1568
		if (!this._taskSystem) {
			return;
		}
1569
		this._taskSystem.terminate(task).then((response) => {
1570
			if (response.success) {
A
Alex Ross 已提交
1571 1572 1573
				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
				});
1574
			} else {
A
Alex Ross 已提交
1575
				this.notificationService.warn(nls.localize('TaskSystem.restartFailed', 'Failed to terminate and restart task {0}', Types.isString(task) ? task : task.configurationProperties.name));
1576 1577 1578 1579 1580
			}
			return response;
		});
	}

J
Johannes Rieken 已提交
1581
	public terminate(task: Task): Promise<TaskTerminateResponse> {
1582
		if (!this._taskSystem) {
1583
			return Promise.resolve({ success: true, task: undefined });
1584
		}
1585
		return this._taskSystem.terminate(task);
1586 1587
	}

J
Johannes Rieken 已提交
1588
	public terminateAll(): Promise<TaskTerminateResponse[]> {
1589
		if (!this._taskSystem) {
1590
			return Promise.resolve<TaskTerminateResponse[]>([]);
1591
		}
1592
		return this._taskSystem.terminateAll();
1593 1594
	}

A
Alex Ross 已提交
1595 1596
	protected createTerminalTaskSystem(): ITaskSystem {
		return new TerminalTaskSystem(
1597
			this.terminalService, this.outputService, this.panelService, this.viewsService, this.markerService,
A
Alex Ross 已提交
1598 1599 1600
			this.modelService, this.configurationResolverService, this.telemetryService,
			this.contextService, this.environmentService,
			AbstractTaskService.OutputChannelId, this.fileService, this.terminalInstanceService,
M
Matt Bierner 已提交
1601
			this.pathService, this.viewDescriptorService, this.logService, this.configurationService,
1602 1603
			(workspaceFolder: IWorkspaceFolder | undefined) => {
				if (workspaceFolder) {
1604
					return this.getTaskSystemInfo(workspaceFolder.uri.scheme);
1605 1606 1607
				} else if (this._taskSystemInfos.size > 0) {
					return this._taskSystemInfos.values().next().value;
				} else {
A
Alex Ross 已提交
1608
					return undefined;
1609
				}
D
Dirk Baeumer 已提交
1610
			}
A
Alex Ross 已提交
1611
		);
1612 1613
	}

A
Alex Ross 已提交
1614 1615
	protected abstract getTaskSystem(): ITaskSystem;

1616 1617
	private isTaskProviderEnabled(type: string) {
		const definition = TaskDefinitionRegistry.get(type);
1618
		return !definition || !definition.when || this.contextKeyService.contextMatchesRules(definition.when);
1619 1620
	}

1621
	private getGroupedTasks(type?: string): Promise<TaskMap> {
1622
		const needsRecentTasksMigration = this.needsRecentTasksMigration();
1623
		return Promise.all([this.extensionService.activateByEvent('onCommand:workbench.action.tasks.runTask'), this.extensionService.whenInstalledExtensionsRegistered()]).then(() => {
1624 1625
			let validTypes: IStringDictionary<boolean> = Object.create(null);
			TaskDefinitionRegistry.all().forEach(definition => validTypes[definition.taskType] = true);
1626 1627
			validTypes['shell'] = true;
			validTypes['process'] = true;
B
Benjamin Pasero 已提交
1628
			return new Promise<TaskSet[]>(resolve => {
D
Dirk Baeumer 已提交
1629 1630
				let result: TaskSet[] = [];
				let counter: number = 0;
1631
				let done = (value: TaskSet | undefined) => {
D
Dirk Baeumer 已提交
1632 1633 1634 1635 1636 1637 1638
					if (value) {
						result.push(value);
					}
					if (--counter === 0) {
						resolve(result);
					}
				};
1639 1640
				let error = (error: any) => {
					try {
1641
						if (error && Types.isString(error.message)) {
1642
							this._outputChannel.append('Error: ');
1643
							this._outputChannel.append(error.message);
1644
							this._outputChannel.append('\n');
1645
							this.showOutput();
1646 1647
						} else {
							this._outputChannel.append('Unknown error received while collecting tasks from providers.\n');
1648
							this.showOutput();
1649 1650 1651 1652 1653
						}
					} finally {
						if (--counter === 0) {
							resolve(result);
						}
D
Dirk Baeumer 已提交
1654 1655
					}
				};
1656
				if (this.isProvideTasksEnabled() && (this.schemaVersion === JsonSchemaVersion.V2_0_0) && (this._providers.size > 0)) {
1657
					for (const [handle, provider] of this._providers) {
1658 1659 1660 1661 1662
						const providerType = this._providerTypes.get(handle);
						if ((type === undefined) || (type === providerType)) {
							if (providerType && !this.isTaskProviderEnabled(providerType)) {
								continue;
							}
1663
							counter++;
1664 1665 1666 1667 1668
							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));
1669 1670 1671
										if ((task.type !== 'shell') && (task.type !== 'process')) {
											this.showOutput();
										}
1672 1673 1674 1675 1676
										break;
									}
								}
								return done(taskSet);
							}, error);
1677 1678
						}
					}
D
Dirk Baeumer 已提交
1679
				} else {
1680 1681
					resolve(result);
				}
D
Dirk Baeumer 已提交
1682
			});
D
Dirk Baeumer 已提交
1683
		}).then((contributedTaskSets) => {
1684 1685
			let result: TaskMap = new TaskMap();
			let contributedTasks: TaskMap = new TaskMap();
1686

D
Dirk Baeumer 已提交
1687 1688
			for (let set of contributedTaskSets) {
				for (let task of set.tasks) {
A
Alex Ross 已提交
1689
					let workspaceFolder = task.getWorkspaceFolder();
D
Dirk Baeumer 已提交
1690
					if (workspaceFolder) {
1691
						contributedTasks.add(workspaceFolder, task);
D
Dirk Baeumer 已提交
1692 1693 1694
					}
				}
			}
1695 1696 1697 1698

			return this.getWorkspaceTasks().then(async (customTasks) => {
				const customTasksKeyValuePairs = Array.from(customTasks);
				const customTasksPromises = customTasksKeyValuePairs.map(async ([key, folderTasks]) => {
D
Dirk Baeumer 已提交
1699
					let contributed = contributedTasks.get(key);
1700 1701
					if (!folderTasks.set) {
						if (contributed) {
1702
							result.add(key, ...contributed);
1703 1704 1705 1706
						}
						return;
					}

1707
					if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
1708
						result.add(key, ...folderTasks.set.tasks);
D
Dirk Baeumer 已提交
1709 1710 1711 1712 1713
					} else {
						let configurations = folderTasks.configurations;
						let legacyTaskConfigurations = folderTasks.set ? this.getLegacyTaskConfigurations(folderTasks.set) : undefined;
						let customTasksToDelete: Task[] = [];
						if (configurations || legacyTaskConfigurations) {
D
Dirk Baeumer 已提交
1714
							let unUsedConfigurations: Set<string> = new Set<string>();
1715 1716 1717
							if (configurations) {
								Object.keys(configurations.byIdentifier).forEach(key => unUsedConfigurations.add(key));
							}
D
Dirk Baeumer 已提交
1718 1719
							for (let task of contributed) {
								if (!ContributedTask.is(task)) {
1720 1721
									continue;
								}
D
Dirk Baeumer 已提交
1722 1723 1724
								if (configurations) {
									let configuringTask = configurations.byIdentifier[task.defines._key];
									if (configuringTask) {
D
Dirk Baeumer 已提交
1725
										unUsedConfigurations.delete(task.defines._key);
1726
										result.add(key, TaskConfig.createCustomTask(task, configuringTask));
D
Dirk Baeumer 已提交
1727
									} else {
1728
										result.add(key, task);
D
Dirk Baeumer 已提交
1729 1730 1731 1732
									}
								} else if (legacyTaskConfigurations) {
									let configuringTask = legacyTaskConfigurations[task.defines._key];
									if (configuringTask) {
1733
										result.add(key, TaskConfig.createCustomTask(task, configuringTask));
D
Dirk Baeumer 已提交
1734
										customTasksToDelete.push(configuringTask);
D
Dirk Baeumer 已提交
1735
									} else {
1736
										result.add(key, task);
D
Dirk Baeumer 已提交
1737 1738
									}
								} else {
1739
									result.add(key, task);
D
Dirk Baeumer 已提交
1740
								}
1741
							}
D
Dirk Baeumer 已提交
1742 1743 1744 1745 1746 1747 1748 1749 1750
							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;
									}
1751
									result.add(key, task);
1752
								}
D
Dirk Baeumer 已提交
1753
							} else {
1754
								result.add(key, ...folderTasks.set.tasks);
1755
							}
1756 1757 1758 1759

							const unUsedConfigurationsAsArray = Array.from(unUsedConfigurations);

							const unUsedConfigurationPromises = unUsedConfigurationsAsArray.map(async (value) => {
1760
								let configuringTask = configurations!.byIdentifier[value];
A
Alex Ross 已提交
1761 1762 1763
								if (type && (type !== configuringTask.configures.type)) {
									return;
								}
1764

1765 1766
								let requiredTaskProviderUnavailable: boolean = false;

1767
								for (const [handle, provider] of this._providers) {
1768 1769 1770 1771 1772 1773 1774
									const providerType = this._providerTypes.get(handle);
									if (configuringTask.type === providerType) {
										if (providerType && !this.isTaskProviderEnabled(providerType)) {
											requiredTaskProviderUnavailable = true;
											continue;
										}

1775 1776
										try {
											const resolvedTask = await provider.resolveTask(configuringTask);
A
Alex Ross 已提交
1777
											if (resolvedTask && (resolvedTask._id === configuringTask._id)) {
1778 1779 1780 1781 1782 1783 1784 1785 1786
												result.add(key, TaskConfig.createCustomTask(resolvedTask, configuringTask));
												return;
											}
										} catch (error) {
											// Ignore errors. The task could not be provided by any of the providers.
										}
									}
								}

1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
								if (requiredTaskProviderUnavailable) {
									this._outputChannel.append(nls.localize(
										'TaskService.providerUnavailable',
										'Warning: {0} tasks are unavailable in the current environment.\n',
										configuringTask.configures.type
									));
								} else {
									this._outputChannel.append(nls.localize(
										'TaskService.noConfiguration',
										'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,
										JSON.stringify(configuringTask._source.config.element, undefined, 4)
									));
									this.showOutput();
								}
D
Dirk Baeumer 已提交
1802
							});
1803 1804

							await Promise.all(unUsedConfigurationPromises);
D
Dirk Baeumer 已提交
1805
						} else {
1806 1807
							result.add(key, ...folderTasks.set.tasks);
							result.add(key, ...contributed);
1808 1809
						}
					}
D
Dirk Baeumer 已提交
1810
				});
1811 1812

				await Promise.all(customTasksPromises);
1813 1814
				if (needsRecentTasksMigration) {
					// At this point we have all the tasks and can migrate the recently used tasks.
1815
					await this.migrateRecentTasks(result.all());
1816
				}
1817 1818 1819
				return result;
			}, () => {
				// If we can't read the tasks.json file provide at least the contributed tasks
1820
				let result: TaskMap = new TaskMap();
D
Dirk Baeumer 已提交
1821
				for (let set of contributedTaskSets) {
1822
					for (let task of set.tasks) {
1823 1824 1825 1826
						const folder = task.getWorkspaceFolder();
						if (folder) {
							result.add(folder, task);
						}
1827
					}
D
Dirk Baeumer 已提交
1828
				}
1829 1830
				return result;
			});
1831 1832 1833
		});
	}

1834
	private getLegacyTaskConfigurations(workspaceTasks: TaskSet): IStringDictionary<CustomTask> | undefined {
1835
		let result: IStringDictionary<CustomTask> | undefined;
1836
		function getResult(): IStringDictionary<CustomTask> {
1837 1838 1839 1840
			if (result) {
				return result;
			}
			result = Object.create(null);
1841
			return result!;
1842 1843
		}
		for (let task of workspaceTasks.tasks) {
1844 1845 1846 1847 1848
			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') {
1849
					let identifier = NKeyedTaskIdentifier.create({
1850
						type: commandName,
A
Alex Ross 已提交
1851
						task: task.configurationProperties.name
1852
					});
1853 1854
					getResult()[identifier._key] = task;
				}
1855 1856 1857 1858 1859
			}
		}
		return result;
	}

1860 1861
	public async getWorkspaceTasks(runSource: TaskRunSource = TaskRunSource.User): Promise<Map<string, WorkspaceFolderTaskResult>> {
		await this._waitForSupportedExecutions;
1862 1863 1864
		if (this._workspaceTasksPromise) {
			return this._workspaceTasksPromise;
		}
1865
		this.updateWorkspaceTasks(runSource);
1866
		return this._workspaceTasksPromise!;
1867 1868
	}

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

A
Alex Ross 已提交
1871
	protected computeWorkspaceTasks(runSource: TaskRunSource = TaskRunSource.User): Promise<Map<string, WorkspaceFolderTaskResult>> {
1872 1873 1874 1875 1876 1877 1878 1879 1880
		let promises: Promise<WorkspaceFolderTaskResult | undefined>[] = [];
		for (let folder of this.workspaceFolders) {
			promises.push(this.computeWorkspaceFolderTasks(folder, runSource).then((value) => value, () => undefined));
		}
		return Promise.all(promises).then(async (values) => {
			let result = new Map<string, WorkspaceFolderTaskResult>();
			for (let value of values) {
				if (value) {
					result.set(value.workspaceFolder.uri.toString(), value);
1881
				}
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
			}
			let folder = this.workspaceFolders.length > 0 ? this.workspaceFolders[0] : undefined;
			if (!folder) {
				const userhome = await this.pathService.userHome();
				folder = new WorkspaceFolder({ uri: userhome, name: resources.basename(userhome), index: 0 });
			}
			const userTasks = await this.computeUserTasks(folder, runSource).then((value) => value, () => undefined);
			if (userTasks) {
				result.set(USER_TASKS_GROUP_KEY, userTasks);
			}

			if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY) {
				const workspaceFileTasks = await this.computeWorkspaceFileTasks(folder, runSource).then((value) => value, () => undefined);
1895 1896 1897
				if (workspaceFileTasks && this._workspace && this._workspace.configuration) {
					result.set(this._workspace.configuration.toString(), workspaceFileTasks);
				}
1898 1899 1900
			}
			return result;
		});
1901 1902
	}

1903 1904
	private get jsonTasksSupported(): boolean {
		return !!ShellExecutionSupportedContext.getValue(this.contextKeyService) && !!ProcessExecutionSupportedContext.getValue(this.contextKeyService);
A
Alex Ross 已提交
1905 1906
	}

1907
	private computeWorkspaceFolderTasks(workspaceFolder: IWorkspaceFolder, runSource: TaskRunSource = TaskRunSource.User): Promise<WorkspaceFolderTaskResult> {
D
Dirk Baeumer 已提交
1908
		return (this.executionEngine === ExecutionEngine.Process
1909 1910 1911 1912
			? this.computeLegacyConfiguration(workspaceFolder)
			: this.computeConfiguration(workspaceFolder)).
			then((workspaceFolderConfiguration) => {
				if (!workspaceFolderConfiguration || !workspaceFolderConfiguration.config || workspaceFolderConfiguration.hasErrors) {
1913
					return Promise.resolve({ workspaceFolder, set: undefined, configurations: undefined, hasErrors: workspaceFolderConfiguration ? workspaceFolderConfiguration.hasErrors : false });
1914
				}
A
Alex Ross 已提交
1915
				return ProblemMatcherRegistry.onReady().then(async (): Promise<WorkspaceFolderTaskResult> => {
1916
					let taskSystemInfo: TaskSystemInfo | undefined = this.getTaskSystemInfo(workspaceFolder.uri.scheme);
1917
					let problemReporter = new ProblemReporter(this._outputChannel);
1918
					let parseResult = TaskConfig.parse(workspaceFolder, undefined, taskSystemInfo ? taskSystemInfo.platform : Platform.platform, workspaceFolderConfiguration.config!, problemReporter, TaskConfig.TaskConfigSource.TasksJson, this.contextKeyService);
1919
					let hasErrors = false;
1920
					if (!parseResult.validationStatus.isOK() && (parseResult.validationStatus.state !== ValidationState.Info)) {
1921
						hasErrors = true;
1922
						this.showOutput(runSource);
1923 1924 1925 1926 1927
					}
					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 };
					}
1928
					let customizedTasks: { byIdentifier: IStringDictionary<ConfiguringTask>; } | undefined;
1929 1930 1931 1932 1933 1934 1935 1936
					if (parseResult.configured && parseResult.configured.length > 0) {
						customizedTasks = {
							byIdentifier: Object.create(null)
						};
						for (let task of parseResult.configured) {
							customizedTasks.byIdentifier[task.configures._key] = task;
						}
					}
1937
					if (!this.jsonTasksSupported && (parseResult.custom.length > 0)) {
A
Alex Ross 已提交
1938 1939
						console.warn('Custom workspace tasks are not supported.');
					}
1940
					return { workspaceFolder, set: { tasks: this.jsonTasksSupported ? parseResult.custom : [] }, configurations: customizedTasks, hasErrors };
1941 1942 1943 1944
				});
			});
	}

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
	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) {
1959
				this._outputChannel.append(nls.localize({ key: 'TaskSystem.invalidTaskJsonOther', comment: ['Message notifies of an error in one of several places there is tasks related json, not necessarily in a file named tasks.json'] }, 'Error: The content of the tasks json in {0} has syntax errors. Please correct them before executing a task.\n', location));
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
				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 已提交
1971
		const configuration = this.testParseExternalConfig(this.configurationService.inspect<TaskConfig.ExternalTaskRunnerConfiguration>('tasks').workspaceValue, nls.localize('TasksSystem.locationWorkspaceConfig', 'workspace file'));
1972 1973 1974 1975 1976 1977 1978 1979
		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) {
1980
			this.notificationService.warn(nls.localize('TaskSystem.versionWorkspaceFile', 'Only tasks version 2.0.0 permitted in workspace configuration files.'));
1981 1982 1983 1984 1985 1986 1987 1988 1989
			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 已提交
1990
		const configuration = this.testParseExternalConfig(this.configurationService.inspect<TaskConfig.ExternalTaskRunnerConfiguration>('tasks').userValue, nls.localize('TasksSystem.locationUserConfig', 'user settings'));
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
		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 };
	}

2009
	private async computeTasksForSingleConfig(workspaceFolder: IWorkspaceFolder, config: TaskConfig.ExternalTaskRunnerConfiguration | undefined, runSource: TaskRunSource, custom: CustomTask[], customized: IStringDictionary<ConfiguringTask>, source: TaskConfig.TaskConfigSource, isRecentTask: boolean = false): Promise<boolean> {
2010 2011 2012
		if (!config) {
			return false;
		}
2013
		let taskSystemInfo: TaskSystemInfo | undefined = workspaceFolder ? this.getTaskSystemInfo(workspaceFolder.uri.scheme) : undefined;
2014
		let problemReporter = new ProblemReporter(this._outputChannel);
2015
		let parseResult = TaskConfig.parse(workspaceFolder, this._workspace, taskSystemInfo ? taskSystemInfo.platform : Platform.platform, config, problemReporter, source, this.contextKeyService, isRecentTask);
2016
		let hasErrors = false;
2017
		if (!parseResult.validationStatus.isOK() && (parseResult.validationStatus.state !== ValidationState.Info)) {
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
			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;
			}
		}
2030
		if (!this.jsonTasksSupported && (parseResult.custom.length > 0)) {
2031 2032 2033 2034 2035 2036 2037 2038 2039
			console.warn('Custom workspace tasks are not supported.');
		} else {
			for (let task of parseResult.custom) {
				custom.push(task);
			}
		}
		return hasErrors;
	}

2040
	private computeConfiguration(workspaceFolder: IWorkspaceFolder): Promise<WorkspaceFolderConfigurationResult> {
2041
		let { config, hasParseErrors } = this.getConfiguration(workspaceFolder);
2042
		return Promise.resolve<WorkspaceFolderConfigurationResult>({ workspaceFolder, config, hasErrors: hasParseErrors });
2043 2044
	}

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

2047
	private computeWorkspaceFolderSetup(): [IWorkspaceFolder[], IWorkspaceFolder[], ExecutionEngine, JsonSchemaVersion, IWorkspace | undefined] {
S
Sandeep Somavarapu 已提交
2048
		let workspaceFolders: IWorkspaceFolder[] = [];
D
Dirk Baeumer 已提交
2049
		let ignoredWorkspaceFolders: IWorkspaceFolder[] = [];
D
Dirk Baeumer 已提交
2050 2051
		let executionEngine = ExecutionEngine.Terminal;
		let schemaVersion = JsonSchemaVersion.V2_0_0;
2052
		let workspace: IWorkspace | undefined;
D
Dirk Baeumer 已提交
2053
		if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
S
Sandeep Somavarapu 已提交
2054
			let workspaceFolder: IWorkspaceFolder = this.contextService.getWorkspace().folders[0];
D
Dirk Baeumer 已提交
2055 2056 2057
			workspaceFolders.push(workspaceFolder);
			executionEngine = this.computeExecutionEngine(workspaceFolder);
			schemaVersion = this.computeJsonSchemaVersion(workspaceFolder);
D
Dirk Baeumer 已提交
2058
		} else if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
2059
			workspace = this.contextService.getWorkspace();
2060
			for (let workspaceFolder of this.contextService.getWorkspace().folders) {
D
Dirk Baeumer 已提交
2061
				if (schemaVersion === this.computeJsonSchemaVersion(workspaceFolder)) {
D
Dirk Baeumer 已提交
2062
					workspaceFolders.push(workspaceFolder);
2063
				} else {
D
Dirk Baeumer 已提交
2064
					ignoredWorkspaceFolders.push(workspaceFolder);
2065 2066
					this._outputChannel.append(nls.localize(
						'taskService.ignoreingFolder',
2067
						'Ignoring task configurations for workspace folder {0}. Multi folder workspace task support requires that all folders use task version 2.0.0\n',
2068
						workspaceFolder.uri.fsPath));
2069 2070 2071
				}
			}
		}
2072
		return [workspaceFolders, ignoredWorkspaceFolders, executionEngine, schemaVersion, workspace];
2073
	}
2074

S
Sandeep Somavarapu 已提交
2075
	private computeExecutionEngine(workspaceFolder: IWorkspaceFolder): ExecutionEngine {
2076
		let { config } = this.getConfiguration(workspaceFolder);
2077
		if (!config) {
2078
			return ExecutionEngine._default;
2079 2080 2081 2082
		}
		return TaskConfig.ExecutionEngine.from(config);
	}

S
Sandeep Somavarapu 已提交
2083
	private computeJsonSchemaVersion(workspaceFolder: IWorkspaceFolder): JsonSchemaVersion {
2084
		let { config } = this.getConfiguration(workspaceFolder);
2085 2086 2087 2088 2089 2090
		if (!config) {
			return JsonSchemaVersion.V2_0_0;
		}
		return TaskConfig.JsonSchemaVersion.from(config);
	}

2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
	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);
			}
		}
2104
		if (!result) {
2105
			return { config: undefined, hasParseErrors: false };
2106 2107 2108 2109
		}
		let parseErrors: string[] = (result as any).$parseErrors;
		if (parseErrors) {
			let isAffected = false;
2110 2111
			for (const parseError of parseErrors) {
				if (/tasks\.json$/.test(parseError)) {
2112 2113 2114
					isAffected = true;
					break;
				}
2115
			}
2116
			if (isAffected) {
2117
				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'));
2118
				this.showOutput();
2119
				return { config: undefined, hasParseErrors: true };
2120
			}
2121 2122
		}
		return { config: result, hasParseErrors: false };
2123 2124
	}

2125
	public inTerminal(): boolean {
2126 2127 2128
		if (this._taskSystem) {
			return this._taskSystem instanceof TerminalTaskSystem;
		}
D
Dirk Baeumer 已提交
2129
		return this.executionEngine === ExecutionEngine.Terminal;
2130 2131
	}

2132
	public configureAction(): Action {
A
Alex Ross 已提交
2133
		const thisCapture: AbstractTaskService = this;
2134 2135
		return new class extends Action {
			constructor() {
2136
				super(ConfigureTaskAction.ID, ConfigureTaskAction.TEXT, undefined, true, () => { thisCapture.runConfigureTasks(); return Promise.resolve(undefined); });
2137 2138
			}
		};
2139 2140
	}

J
Johannes Rieken 已提交
2141
	private handleError(err: any): void {
E
Erich Gamma 已提交
2142 2143 2144
		let showOutput = true;
		if (err instanceof TaskError) {
			let buildError = <TaskError>err;
2145 2146 2147
			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 已提交
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
				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 已提交
2158
			} else {
2159
				this.notificationService.notify({ severity: buildError.severity, message: buildError.message });
E
Erich Gamma 已提交
2160 2161 2162
			}
		} else if (err instanceof Error) {
			let error = <Error>err;
2163
			this.notificationService.error(error.message);
2164
			showOutput = false;
E
Erich Gamma 已提交
2165
		} else if (Types.isString(err)) {
2166
			this.notificationService.error(<string>err);
E
Erich Gamma 已提交
2167
		} else {
2168
			this.notificationService.error(nls.localize('TaskSystem.unknownError', 'An error has occurred while running a task. See task log for details.'));
E
Erich Gamma 已提交
2169 2170
		}
		if (showOutput) {
2171
			this.showOutput();
E
Erich Gamma 已提交
2172 2173
		}
	}
2174 2175 2176 2177 2178

	private canRunCommand(): boolean {
		return true;
	}

2179 2180 2181 2182
	private showDetail(): boolean {
		return this.configurationService.getValue<boolean>(QUICKOPEN_DETAIL_CONFIG);
	}

2183
	private async createTaskQuickPickEntries(tasks: Task[], group: boolean = false, sort: boolean = false, selectedEntry?: TaskQuickPickEntry, includeRecents: boolean = true): Promise<TaskQuickPickEntry[]> {
2184
		let count: { [key: string]: number; } = {};
R
Rob Lourens 已提交
2185
		if (tasks === undefined || tasks === null || tasks.length === 0) {
2186
			return [];
2187
		}
2188
		const TaskQuickPickEntry = (task: Task): TaskQuickPickEntry => {
2189
			let entryLabel = task._label;
2190 2191 2192
			if (count[task._id]) {
				entryLabel = entryLabel + ' (' + count[task._id].toString() + ')';
				count[task._id]++;
2193
			} else {
2194
				count[task._id] = 1;
2195 2196 2197
			}
			return { label: entryLabel, description: this.getTaskDescription(task), task, detail: this.showDetail() ? task.configurationProperties.detail : undefined };

2198
		};
C
Christof Marti 已提交
2199
		function fillEntries(entries: QuickPickInput<TaskQuickPickEntry>[], tasks: Task[], groupLabel: string): void {
C
Christof Marti 已提交
2200
			if (tasks.length) {
C
Christof Marti 已提交
2201
				entries.push({ type: 'separator', label: groupLabel });
2202
			}
2203
			for (let task of tasks) {
2204
				let entry: TaskQuickPickEntry = TaskQuickPickEntry(task);
M
Martin Aeschlimann 已提交
2205
				entry.buttons = [{ iconClass: ThemeIcon.asClassName(configureTaskIcon), tooltip: nls.localize('configureTask', "Configure Task") }];
2206 2207 2208 2209 2210
				if (selectedEntry && (task === selectedEntry.task)) {
					entries.unshift(selectedEntry);
				} else {
					entries.push(entry);
				}
2211 2212
			}
		}
2213
		let entries: TaskQuickPickEntry[];
2214 2215 2216
		if (group) {
			entries = [];
			if (tasks.length === 1) {
2217
				entries.push(TaskQuickPickEntry(tasks[0]));
2218
			} else {
2219
				let recentlyUsedTasks = await this.readRecentTasks();
2220
				let recent: Task[] = [];
2221
				let recentSet: Set<string> = new Set();
2222 2223 2224
				let configured: Task[] = [];
				let detected: Task[] = [];
				let taskMap: IStringDictionary<Task> = Object.create(null);
2225
				tasks.forEach(task => {
2226
					let key = task.getCommonTaskId();
2227 2228 2229 2230
					if (key) {
						taskMap[key] = task;
					}
				});
2231 2232 2233 2234 2235 2236 2237 2238
				recentlyUsedTasks.reverse().forEach(recentTask => {
					const key = recentTask.getCommonTaskId();
					if (key) {
						recentSet.add(key);
						let task = taskMap[key];
						if (task) {
							recent.push(task);
						}
2239 2240 2241
					}
				});
				for (let task of tasks) {
2242 2243
					let key = task.getCommonTaskId();
					if (!key || !recentSet.has(key)) {
2244
						if ((task._source.kind === TaskSourceKind.Workspace) || (task._source.kind === TaskSourceKind.User)) {
2245 2246 2247 2248 2249 2250
							configured.push(task);
						} else {
							detected.push(task);
						}
					}
				}
2251
				const sorter = this.createSorter();
2252 2253 2254
				if (includeRecents) {
					fillEntries(entries, recent, nls.localize('recentlyUsed', 'recently used tasks'));
				}
2255
				configured = configured.sort((a, b) => sorter.compare(a, b));
C
Christof Marti 已提交
2256
				fillEntries(entries, configured, nls.localize('configured', 'configured tasks'));
2257
				detected = detected.sort((a, b) => sorter.compare(a, b));
C
Christof Marti 已提交
2258
				fillEntries(entries, detected, nls.localize('detected', 'detected tasks'));
2259 2260 2261
			}
		} else {
			if (sort) {
2262 2263
				const sorter = this.createSorter();
				tasks = tasks.sort((a, b) => sorter.compare(a, b));
2264
			}
2265
			entries = tasks.map<TaskQuickPickEntry>(task => TaskQuickPickEntry(task));
2266
		}
2267
		count = {};
2268 2269 2270
		return entries;
	}

A
Alex Ross 已提交
2271
	private async showTwoLevelQuickPick(placeHolder: string, defaultEntry?: TaskQuickPickEntry) {
2272
		return TaskQuickPick.show(this, this.configurationService, this.quickInputService, this.notificationService, placeHolder, defaultEntry);
A
Alex Ross 已提交
2273 2274
	}

2275
	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> {
2276 2277
		const tokenSource = new CancellationTokenSource();
		const cancellationToken: CancellationToken = tokenSource.token;
2278
		let _createEntries = new Promise<QuickPickInput<TaskQuickPickEntry>[]>((resolve) => {
2279
			if (Array.isArray(tasks)) {
2280
				resolve(this.createTaskQuickPickEntries(tasks, group, sort, selectedEntry));
2281
			} else {
2282
				resolve(tasks.then((tasks) => this.createTaskQuickPickEntries(tasks, group, sort, selectedEntry)));
2283
			}
2284 2285
		});

2286
		const timeout: boolean = await Promise.race([new Promise<boolean>(async (resolve) => {
2287 2288
			await _createEntries;
			resolve(false);
2289
		}), new Promise<boolean>((resolve) => {
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
			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) => {
2301 2302 2303
			if ((entries.length === 1) && this.configurationService.getValue<boolean>(QUICKOPEN_SKIP_CONFIG)) {
				tokenSource.cancel();
			} else if ((entries.length === 0) && defaultEntry) {
2304
				entries.push(defaultEntry);
A
Alex Ross 已提交
2305 2306
			} else if (entries.length > 1 && additionalEntries && additionalEntries.length > 0) {
				entries.push({ type: 'separator', label: '' });
2307 2308
				entries.push(additionalEntries[0]);
			}
2309
			return entries;
2310
		});
2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322

		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);
2323
			}
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
		});
		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) {
2344
					resolve(undefined);
2345 2346 2347
				}
				resolve(selection);
			}));
M
Matt Bierner 已提交
2348
		});
2349 2350
	}

2351 2352 2353 2354
	private needsRecentTasksMigration(): boolean {
		return (this.getRecentlyUsedTasksV1().size > 0) && (this.getRecentlyUsedTasks().size === 0);
	}

2355
	public async migrateRecentTasks(tasks: Task[]) {
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
		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;
			}
		});
2367
		const reversed = [...recentlyUsedTasks.keys()].reverse();
2368
		for (const key in reversed) {
2369 2370
			let task = taskMap[key];
			if (task) {
2371
				await this.setRecentlyUsedTask(task);
2372
			}
2373
		}
2374 2375 2376
		this.storageService.remove(AbstractTaskService.RecentlyUsedTasks_Key, StorageScope.WORKSPACE);
	}

J
Johannes Rieken 已提交
2377
	private showIgnoredFoldersMessage(): Promise<void> {
D
Dirk Baeumer 已提交
2378
		if (this.ignoredWorkspaceFolders.length === 0 || !this.showIgnoreMessage) {
2379
			return Promise.resolve(undefined);
D
Dirk Baeumer 已提交
2380 2381
		}

2382 2383 2384 2385
		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 已提交
2386
				label: nls.localize('TaskService.notAgain', "Don't Show Again"),
2387 2388
				isSecondary: true,
				run: () => {
2389
					this.storageService.store(AbstractTaskService.IgnoreTask010DonotShowAgain_key, true, StorageScope.WORKSPACE, StorageTarget.USER);
2390
					this._showIgnoreMessage = false;
2391 2392 2393
				}
			}]
		);
2394

2395
		return Promise.resolve(undefined);
D
Dirk Baeumer 已提交
2396 2397
	}

2398
	private runTaskCommand(arg?: any): void {
2399 2400 2401
		if (!this.canRunCommand()) {
			return;
		}
2402
		let identifier = this.getTaskIdentifier(arg);
R
Rob Lourens 已提交
2403
		if (identifier !== undefined) {
A
Alex Ross 已提交
2404
			this.getGroupedTasks().then(async (grouped) => {
2405
				let resolver = this.createResolver(grouped);
2406 2407 2408 2409 2410 2411 2412
				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);
2413
					if (task) {
A
Alex Ross 已提交
2414 2415 2416
						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
						});
2417 2418
						return;
					}
2419
				}
2420
				this.doRunTaskCommand(grouped.all());
2421
			}, () => {
2422
				this.doRunTaskCommand();
2423 2424
			});
		} else {
2425
			this.doRunTaskCommand();
2426 2427 2428
		}
	}

2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
	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 已提交
2452
					}
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
				}
			});
			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 已提交
2470
				});
2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
			}
		};

		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,
					{
2484
						label: nls.localize('TaskService.noEntryToRunSlow', '$(plus) Configure a Task'),
2485 2486 2487 2488 2489 2490 2491 2492 2493
						task: null
					},
					true).
					then((entry) => {
						return pickThen(entry ? entry.task : undefined);
					});
			} else {
				this.showTwoLevelQuickPick(placeholder,
					{
2494
						label: nls.localize('TaskService.noEntryToRun', '$(plus) Configure a Task'),
2495 2496 2497 2498
						task: null
					}).
					then(pickThen);
			}
D
Dirk Baeumer 已提交
2499
		});
2500 2501
	}

2502
	private reRunTaskCommand(): void {
A
Alex Ross 已提交
2503 2504 2505 2506 2507
		if (!this.canRunCommand()) {
			return;
		}

		ProblemMatcherRegistry.onReady().then(() => {
2508
			return this.editorService.saveAll({ reason: SaveReason.AUTO }).then(() => { // make sure all dirty editors are saved
A
Alex Ross 已提交
2509 2510 2511 2512 2513
				let executeResult = this.getTaskSystem().rerun();
				if (executeResult) {
					return this.handleExecuteResult(executeResult);
				} else {
					this.doRunTaskCommand();
2514
					return Promise.resolve(undefined);
A
Alex Ross 已提交
2515 2516 2517 2518 2519
				}
			});
		});
	}

2520 2521 2522 2523 2524
	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 已提交
2525
			if (task.configurationProperties.groupType === GroupType.default) {
2526
				defaults.push(task);
A
Alex Ross 已提交
2527
			} else if (task.configurationProperties.groupType === GroupType.user) {
2528 2529 2530 2531 2532 2533 2534 2535
				users.push(task);
			} else {
				none.push(task);
			}
		}
		return { none, defaults, users };
	}

2536 2537 2538 2539
	private runBuildCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2540
		if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
2541 2542 2543
			this.build();
			return;
		}
2544 2545 2546 2547
		let options: IProgressOptions = {
			location: ProgressLocation.Window,
			title: nls.localize('TaskService.fetchingBuildTasks', 'Fetching build tasks...')
		};
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
		let promise = this.getWorkspaceTasks().then(tasks => {
			const buildTasks: ConfiguringTask[] = [];
			for (const taskSource of tasks) {
				for (const task in taskSource[1].configurations?.byIdentifier) {
					if ((taskSource[1].configurations?.byIdentifier[task].configurationProperties.group === TaskGroup.Build) &&
						(taskSource[1].configurations?.byIdentifier[task].configurationProperties.groupType === GroupType.default)) {
						buildTasks.push(taskSource[1].configurations.byIdentifier[task]);
					}
				}
			}
			if (buildTasks.length === 1) {
				this.tryResolveTask(buildTasks[0]).then(resolvedTask => {
2560
					this.run(resolvedTask, undefined, TaskRunSource.User).then(undefined, reason => {
A
Alex Ross 已提交
2561 2562
						// eat the error, it has already been surfaced to the user and we don't care about it here
					});
2563 2564
				});
				return;
D
Dirk Baeumer 已提交
2565
			}
2566 2567 2568 2569 2570

			return this.getTasksForGroup(TaskGroup.Build).then((tasks) => {
				if (tasks.length > 0) {
					let { defaults, users } = this.splitPerGroupType(tasks);
					if (defaults.length === 1) {
2571
						this.run(defaults[0], undefined, TaskRunSource.User).then(undefined, reason => {
A
Alex Ross 已提交
2572 2573
							// eat the error, it has already been surfaced to the user and we don't care about it here
						});
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
						return;
					} else if (defaults.length + users.length > 0) {
						tasks = defaults.concat(users);
					}
				}
				this.showIgnoredFoldersMessage().then(() => {
					this.showQuickPick(tasks,
						nls.localize('TaskService.pickBuildTask', 'Select the build task to run'),
						{
							label: nls.localize('TaskService.noBuildTask', 'No build task to run found. Configure Build Task...'),
							task: null
						},
						true).then((entry) => {
							let task: Task | undefined | null = entry ? entry.task : undefined;
							if (task === undefined) {
								return;
							}
							if (task === null) {
								this.runConfigureDefaultBuildTask();
								return;
							}
2595
							this.run(task, { attachProblemMatcher: true }, TaskRunSource.User).then(undefined, reason => {
2596 2597 2598 2599
								// eat the error, it has already been surfaced to the user and we don't care about it here
							});
						});
				});
D
Dirk Baeumer 已提交
2600
			});
2601
		});
2602
		this.progressService.withProgress(options, () => promise);
2603 2604 2605 2606 2607 2608
	}

	private runTestCommand(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2609
		if (this.schemaVersion === JsonSchemaVersion.V0_1_0) {
2610
			this.runTest();
2611 2612
			return;
		}
2613 2614 2615 2616 2617
		let options: IProgressOptions = {
			location: ProgressLocation.Window,
			title: nls.localize('TaskService.fetchingTestTasks', 'Fetching test tasks...')
		};
		let promise = this.getTasksForGroup(TaskGroup.Test).then((tasks) => {
2618
			if (tasks.length > 0) {
D
Dirk Baeumer 已提交
2619
				let { defaults, users } = this.splitPerGroupType(tasks);
2620
				if (defaults.length === 1) {
2621
					this.run(defaults[0], undefined, TaskRunSource.User).then(undefined, reason => {
A
Alex Ross 已提交
2622 2623
						// eat the error, it has already been surfaced to the user and we don't care about it here
					});
2624
					return;
2625 2626
				} else if (defaults.length + users.length > 0) {
					tasks = defaults.concat(users);
D
Dirk Baeumer 已提交
2627 2628
				}
			}
D
Dirk Baeumer 已提交
2629 2630 2631 2632 2633 2634 2635
			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
2636 2637
				).then((entry) => {
					let task: Task | undefined | null = entry ? entry.task : undefined;
R
Rob Lourens 已提交
2638
					if (task === undefined) {
D
Dirk Baeumer 已提交
2639 2640 2641 2642 2643 2644
						return;
					}
					if (task === null) {
						this.runConfigureTasks();
						return;
					}
2645
					this.run(task, undefined, TaskRunSource.User).then(undefined, reason => {
A
Alex Ross 已提交
2646 2647
						// eat the error, it has already been surfaced to the user and we don't care about it here
					});
D
Dirk Baeumer 已提交
2648
				});
2649
			});
2650
		});
2651
		this.progressService.withProgress(options, () => promise);
2652 2653
	}

2654
	private runTerminateCommand(arg?: any): void {
2655 2656 2657
		if (!this.canRunCommand()) {
			return;
		}
2658 2659 2660 2661
		if (arg === 'terminateAll') {
			this.terminateAll();
			return;
		}
J
Johannes Rieken 已提交
2662
		let runQuickPick = (promise?: Promise<Task[]>) => {
2663
			this.showQuickPick(promise || this.getActiveTasks(),
A
Alex Ross 已提交
2664
				nls.localize('TaskService.taskToTerminate', 'Select a task to terminate'),
2665 2666
				{
					label: nls.localize('TaskService.noTaskRunning', 'No task is currently running'),
2667
					task: undefined
2668
				},
2669 2670 2671
				false, true,
				undefined,
				[{
A
Alex Ross 已提交
2672
					label: nls.localize('TaskService.terminateAllRunningTasks', 'All Running Tasks'),
2673 2674 2675 2676 2677 2678 2679 2680
					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 已提交
2681
				if (task === undefined || task === null) {
2682 2683
					return;
				}
2684
				this.terminate(task);
2685
			});
2686 2687 2688
		};
		if (this.inTerminal()) {
			let identifier = this.getTaskIdentifier(arg);
J
Johannes Rieken 已提交
2689
			let promise: Promise<Task[]>;
R
Rob Lourens 已提交
2690
			if (identifier !== undefined) {
2691 2692 2693
				promise = this.getActiveTasks();
				promise.then((tasks) => {
					for (let task of tasks) {
A
Alex Ross 已提交
2694
						if (task.matches(identifier)) {
2695 2696 2697 2698 2699 2700 2701 2702 2703
							this.terminate(task);
							return;
						}
					}
					runQuickPick(promise);
				});
			} else {
				runQuickPick();
			}
2704 2705 2706
		} else {
			this.isActive().then((active) => {
				if (active) {
2707 2708 2709
					this.terminateAll().then((responses) => {
						// the output runner has only one task
						let response = responses[0];
2710
						if (response.success) {
2711 2712 2713
							return;
						}
						if (response.code && response.code === TerminateResponseCode.ProcessNotFound) {
2714
							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.'));
2715
						} else {
2716
							this.notificationService.error(nls.localize('TerminateAction.failed', 'Failed to terminate running task'));
2717 2718 2719 2720 2721 2722
						}
					});
				}
			});
		}
	}
2723

2724
	private runRestartTaskCommand(arg?: any): void {
2725 2726 2727
		if (!this.canRunCommand()) {
			return;
		}
J
Johannes Rieken 已提交
2728
		let runQuickPick = (promise?: Promise<Task[]>) => {
2729
			this.showQuickPick(promise || this.getActiveTasks(),
2730
				nls.localize('TaskService.taskToRestart', 'Select the task to restart'),
2731 2732 2733 2734 2735
				{
					label: nls.localize('TaskService.noTaskToRestart', 'No task to restart'),
					task: null
				},
				false, true
2736 2737
			).then(entry => {
				let task: Task | undefined | null = entry ? entry.task : undefined;
R
Rob Lourens 已提交
2738
				if (task === undefined || task === null) {
2739 2740
					return;
				}
2741
				this.restart(task);
2742
			});
2743 2744 2745
		};
		if (this.inTerminal()) {
			let identifier = this.getTaskIdentifier(arg);
J
Johannes Rieken 已提交
2746
			let promise: Promise<Task[]>;
R
Rob Lourens 已提交
2747
			if (identifier !== undefined) {
2748 2749 2750
				promise = this.getActiveTasks();
				promise.then((tasks) => {
					for (let task of tasks) {
A
Alex Ross 已提交
2751
						if (task.matches(identifier)) {
2752 2753 2754 2755 2756 2757 2758 2759 2760
							this.restart(task);
							return;
						}
					}
					runQuickPick(promise);
				});
			} else {
				runQuickPick();
			}
2761 2762 2763 2764 2765 2766 2767 2768 2769 2770
		} else {
			this.getActiveTasks().then((activeTasks) => {
				if (activeTasks.length === 0) {
					return;
				}
				let task = activeTasks[0];
				this.restart(task);
			});
		}
	}
2771

2772
	private getTaskIdentifier(arg?: any): string | KeyedTaskIdentifier | undefined {
2773
		let result: string | KeyedTaskIdentifier | undefined = undefined;
2774 2775 2776 2777 2778 2779 2780 2781
		if (Types.isString(arg)) {
			result = arg;
		} else if (arg && Types.isString((arg as TaskIdentifier).type)) {
			result = TaskDefinition.createTaskIdentifier(arg as TaskIdentifier, console);
		}
		return result;
	}

2782 2783 2784 2785
	private configHasTasks(taskConfig?: TaskConfig.ExternalTaskRunnerConfiguration): boolean {
		return !!taskConfig && !!taskConfig.tasks && taskConfig.tasks.length > 0;
	}

2786
	private openTaskFile(resource: URI, taskSource: string) {
2787
		let configFileCreated = false;
2788 2789 2790 2791 2792 2793
		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) {
2794 2795 2796
				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;
2797 2798 2799 2800 2801
			}
			let content;
			if (!tasksExistInFile) {
				const pickTemplateResult = await this.quickInputService.pick(getTaskTemplates(), { placeHolder: nls.localize('TaskService.template', 'Select a Task Template') });
				if (!pickTemplateResult) {
2802 2803
					return Promise.resolve(undefined);
				}
2804
				content = pickTemplateResult.content;
2805 2806
				let editorConfig = this.configurationService.getValue<any>();
				if (editorConfig.editor.insertSpaces) {
2807
					content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + ' '.repeat(s2.length * editorConfig.editor.tabSize));
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
				}
				configFileCreated = true;
				type TaskServiceTemplateClassification = {
					templateId?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
					autoDetect: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
				};
				type TaskServiceEvent = {
					templateId?: string;
					autoDetect: boolean;
				};
2818 2819 2820 2821 2822 2823 2824
				this.telemetryService.publicLog2<TaskServiceEvent, TaskServiceTemplateClassification>('taskService.template', {
					templateId: pickTemplateResult.id,
					autoDetect: pickTemplateResult.autoDetect
				});
			}

			if (!fileExists && content) {
2825 2826 2827
				return this.textFileService.create(resource, content).then((result): URI => {
					return result.resource;
				});
2828 2829 2830 2831 2832 2833 2834
			} else if (fileExists && (tasksExistInFile || content)) {
				if (content) {
					this.configurationService.updateValue('tasks', json.parse(content), target);
				}
				return stat?.resource;
			}
			return undefined;
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
		}).then((resource) => {
			if (!resource) {
				return;
			}
			this.editorService.openEditor({
				resource,
				options: {
					pinned: configFileCreated // pin only if config file is created #8727
				}
			});
		});
	}

A
Alex Ross 已提交
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862
	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.
		}
	}

2863
	private handleSelection(selection: TaskQuickPickEntryType | undefined) {
A
Alex Ross 已提交
2864 2865 2866 2867 2868
		if (!selection) {
			return;
		}
		if (this.isTaskEntry(selection)) {
			this.configureTask(selection.task);
2869
		} else if (selection.folder && (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY)) {
2870
			this.openTaskFile(selection.folder.toResource('.vscode/tasks.json'), TaskSourceKind.Workspace);
2871 2872 2873 2874 2875
		} else {
			const resource = this.getResourceForKind(TaskSourceKind.User);
			if (resource) {
				this.openTaskFile(resource, TaskSourceKind.User);
			}
A
Alex Ross 已提交
2876 2877
		}
	}
2878

A
Alex Ross 已提交
2879
	public getTaskDescription(task: Task | ConfiguringTask): string | undefined {
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893
		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;
	}

2894
	private async runConfigureTasks(): Promise<void> {
2895 2896 2897
		if (!this.canRunCommand()) {
			return undefined;
		}
J
Johannes Rieken 已提交
2898
		let taskPromise: Promise<TaskMap>;
D
Dirk Baeumer 已提交
2899
		if (this.schemaVersion === JsonSchemaVersion.V2_0_0) {
2900 2901
			taskPromise = this.getGroupedTasks();
		} else {
2902
			taskPromise = Promise.resolve(new TaskMap());
2903 2904
		}

2905
		let stats = this.contextService.getWorkspace().folders.map<Promise<IFileStat | undefined>>((folder) => {
B
Benjamin Pasero 已提交
2906
			return this.fileService.resolve(folder.toResource('.vscode/tasks.json')).then(stat => stat, () => undefined);
2907 2908 2909 2910
		});

		let createLabel = nls.localize('TaskService.createJsonFile', 'Create tasks.json file from template');
		let openLabel = nls.localize('TaskService.openJsonFile', 'Open tasks.json file');
2911 2912
		const tokenSource = new CancellationTokenSource();
		const cancellationToken: CancellationToken = tokenSource.token;
2913
		let entries = Promise.all(stats).then((stats) => {
2914
			return taskPromise.then((taskMap) => {
A
Alex Ross 已提交
2915
				let entries: QuickPickInput<TaskQuickPickEntryType>[] = [];
2916
				let needsCreateOrOpen: boolean = true;
2917 2918 2919 2920 2921 2922 2923
				let tasks = taskMap.all();
				if (tasks.length > 0) {
					tasks = tasks.sort((a, b) => a._label.localeCompare(b._label));
					for (let task of tasks) {
						entries.push({ label: task._label, task, description: this.getTaskDescription(task), detail: this.showDetail() ? task.configurationProperties.detail : undefined });
						if (!ContributedTask.is(task)) {
							needsCreateOrOpen = false;
C
Christof Marti 已提交
2924
						}
2925
					}
2926 2927 2928 2929 2930
				}
				if (needsCreateOrOpen) {
					let label = stats[0] !== undefined ? openLabel : createLabel;
					if (entries.length) {
						entries.push({ type: 'separator' });
2931
					}
2932
					entries.push({ label, folder: this.contextService.getWorkspace().folders[0] });
2933
				}
2934
				if ((entries.length === 1) && !needsCreateOrOpen) {
2935 2936
					tokenSource.cancel();
				}
2937 2938 2939 2940
				return entries;
			});
		});

2941
		const timeout: boolean = await Promise.race([new Promise<boolean>(async (resolve) => {
2942 2943
			await entries;
			resolve(false);
2944
		}), new Promise<boolean>((resolve) => {
2945 2946 2947 2948 2949 2950 2951
			const timer = setTimeout(() => {
				clearTimeout(timer);
				resolve(true);
			}, 200);
		})]);

		if (!timeout && ((await entries).length === 1) && this.configurationService.getValue<boolean>(QUICKOPEN_SKIP_CONFIG)) {
A
Alex Ross 已提交
2952 2953
			const entry: any = <any>((await entries)[0]);
			if (entry.task) {
A
Alex Ross 已提交
2954
				this.handleSelection(entry);
A
Alex Ross 已提交
2955 2956
				return;
			}
2957 2958
		}

C
Christof Marti 已提交
2959
		this.quickInputService.pick(entries,
2960 2961 2962 2963 2964 2965
			{ 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 已提交
2966
						selection = <TaskQuickPickEntryType>task;
2967 2968
					}
				}
A
Alex Ross 已提交
2969
				this.handleSelection(selection);
D
Dirk Baeumer 已提交
2970
			});
2971 2972
	}

2973 2974 2975 2976
	private runConfigureDefaultBuildTask(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
2977
		if (this.schemaVersion === JsonSchemaVersion.V2_0_0) {
2978 2979
			this.tasks().then((tasks => {
				if (tasks.length === 0) {
2980
					this.runConfigureTasks();
2981 2982
					return;
				}
2983
				let selectedTask: Task | undefined;
2984
				let selectedEntry: TaskQuickPickEntry;
2985
				for (let task of tasks) {
A
Alex Ross 已提交
2986
					if (task.configurationProperties.group === TaskGroup.Build && task.configurationProperties.groupType === GroupType.default) {
2987
						selectedTask = task;
2988 2989 2990
						break;
					}
				}
2991 2992
				if (selectedTask) {
					selectedEntry = {
A
Alex Ross 已提交
2993
						label: nls.localize('TaskService.defaultBuildTaskExists', '{0} is already marked as the default build task', selectedTask.getQualifiedLabel()),
2994 2995
						task: selectedTask,
						detail: this.showDetail() ? selectedTask.configurationProperties.detail : undefined
2996
					};
2997
				}
D
Dirk Baeumer 已提交
2998 2999
				this.showIgnoredFoldersMessage().then(() => {
					this.showQuickPick(tasks,
3000
						nls.localize('TaskService.pickDefaultBuildTask', 'Select the task to be used as the default build task'), undefined, true, false, selectedEntry).
3001 3002
						then((entry) => {
							let task: Task | undefined | null = entry ? entry.task : undefined;
3003
							if ((task === undefined) || (task === null)) {
D
Dirk Baeumer 已提交
3004 3005
								return;
							}
3006
							if (task === selectedTask && CustomTask.is(task)) {
D
Dirk Baeumer 已提交
3007 3008 3009
								this.openConfig(task);
							}
							if (!InMemoryTask.is(task)) {
3010 3011
								this.customize(task, { group: { kind: 'build', isDefault: true } }, true).then(() => {
									if (selectedTask && (task !== selectedTask) && !InMemoryTask.is(selectedTask)) {
3012
										this.customize(selectedTask, { group: 'build' }, false);
3013 3014
									}
								});
D
Dirk Baeumer 已提交
3015 3016 3017
							}
						});
				});
3018 3019
			}));
		} else {
3020
			this.runConfigureTasks();
3021 3022 3023 3024 3025 3026 3027
		}
	}

	private runConfigureDefaultTestTask(): void {
		if (!this.canRunCommand()) {
			return;
		}
D
Dirk Baeumer 已提交
3028
		if (this.schemaVersion === JsonSchemaVersion.V2_0_0) {
3029 3030
			this.tasks().then((tasks => {
				if (tasks.length === 0) {
3031
					this.runConfigureTasks();
3032
					return;
3033
				}
3034
				let selectedTask: Task | undefined;
3035 3036
				let selectedEntry: TaskQuickPickEntry;

3037
				for (let task of tasks) {
A
Alex Ross 已提交
3038
					if (task.configurationProperties.group === TaskGroup.Test && task.configurationProperties.groupType === GroupType.default) {
3039
						selectedTask = task;
3040 3041 3042
						break;
					}
				}
3043 3044
				if (selectedTask) {
					selectedEntry = {
A
Alex Ross 已提交
3045
						label: nls.localize('TaskService.defaultTestTaskExists', '{0} is already marked as the default test task.', selectedTask.getQualifiedLabel()),
3046 3047
						task: selectedTask,
						detail: this.showDetail() ? selectedTask.configurationProperties.detail : undefined
3048
					};
3049
				}
3050

D
Dirk Baeumer 已提交
3051
				this.showIgnoredFoldersMessage().then(() => {
3052
					this.showQuickPick(tasks,
3053 3054
						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;
3055 3056 3057 3058 3059 3060 3061 3062 3063
							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)) {
3064
										this.customize(selectedTask, { group: 'test' }, false);
3065 3066 3067 3068
									}
								});
							}
						});
3069 3070 3071
				});
			}));
		} else {
3072
			this.runConfigureTasks();
3073 3074
		}
	}
3075

3076
	public async runShowTasks(): Promise<void> {
3077 3078 3079
		if (!this.canRunCommand()) {
			return;
		}
3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
		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);
			});
		}
3099
	}
3100
}