terminalTaskSystem.ts 54.5 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import * as path from 'vs/base/common/path';
7 8
import * as nls from 'vs/nls';
import * as Objects from 'vs/base/common/objects';
9
import * as Types from 'vs/base/common/types';
10 11
import * as Platform from 'vs/base/common/platform';
import * as Async from 'vs/base/common/async';
12
import * as resources from 'vs/base/common/resources';
13
import { IStringDictionary, values } from 'vs/base/common/collections';
14
import { LinkedMap, Touch } from 'vs/base/common/map';
15
import Severity from 'vs/base/common/severity';
M
Matt Bierner 已提交
16
import { Event, Emitter } from 'vs/base/common/event';
17
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
18
import { isUNC } from 'vs/base/common/extpath';
19

20
import { IFileService } from 'vs/platform/files/common/files';
21
import { IMarkerService, MarkerSeverity } from 'vs/platform/markers/common/markers';
22
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
23
import { IModelService } from 'vs/editor/common/services/modelService';
24
import { ProblemMatcher, ProblemMatcherRegistry /*, ProblemPattern, getResource */ } from 'vs/workbench/contrib/tasks/common/problemMatcher';
25
import Constants from 'vs/workbench/contrib/markers/browser/constants';
26

27 28 29
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';

import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
30
import { ITerminalService, ITerminalInstance, IShellLaunchConfig } from 'vs/workbench/contrib/terminal/common/terminal';
31
import { IOutputService } from 'vs/workbench/contrib/output/common/output';
32
import { StartStopProblemCollector, WatchingProblemCollector, ProblemCollectorEventKind, ProblemHandlingStrategy } from 'vs/workbench/contrib/tasks/common/problemCollectors';
33 34
import {
	Task, CustomTask, ContributedTask, RevealKind, CommandOptions, ShellConfiguration, RuntimeType, PanelKind,
35
	TaskEvent, TaskEventKind, ShellQuotingOptions, ShellQuoting, CommandString, CommandConfiguration, ExtensionTaskSource, TaskScope, RevealProblemKind, DependsOrder
36
} from 'vs/workbench/contrib/tasks/common/tasks';
37
import {
38
	ITaskSystem, ITaskSummary, ITaskExecuteResult, TaskExecuteKind, TaskError, TaskErrors, ITaskResolver,
A
Alex Ross 已提交
39
	TelemetryEvent, Triggers, TaskTerminateResponse, TaskSystemInfoResolver, TaskSystemInfo, ResolveSet, ResolvedVariables
40
} from 'vs/workbench/contrib/tasks/common/taskSystem';
A
Alex Ross 已提交
41
import { URI } from 'vs/base/common/uri';
42
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
A
Alex Ross 已提交
43
import { Schemas } from 'vs/base/common/network';
44
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
45
import { ITerminalInstanceService } from 'vs/workbench/contrib/terminal/browser/terminal';
A
Alex Ross 已提交
46
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
47

D
Dirk Baeumer 已提交
48 49 50
interface TerminalData {
	terminal: ITerminalInstance;
	lastTask: string;
51
	group?: string;
D
Dirk Baeumer 已提交
52 53 54 55
}

interface ActiveTerminalData {
	terminal: ITerminalInstance;
56
	task: Task;
57
	promise: Promise<ITaskSummary>;
D
Dirk Baeumer 已提交
58 59
}

60 61 62 63 64 65
class VariableResolver {

	constructor(public workspaceFolder: IWorkspaceFolder, public taskSystemInfo: TaskSystemInfo | undefined, private _values: Map<string, string>, private _service: IConfigurationResolverService | undefined) {
	}
	resolve(value: string): string {
		return value.replace(/\$\{(.*?)\}/g, (match: string, variable: string) => {
A
Alex Ross 已提交
66 67
			// Strip out the ${} because the map contains them variables without those characters.
			let result = this._values.get(match.substring(2, match.length - 1));
68
			if ((result !== undefined) && (result !== null)) {
69 70 71 72 73 74 75 76 77 78
				return result;
			}
			if (this._service) {
				return this._service.resolve(this.workspaceFolder, match);
			}
			return match;
		});
	}
}

A
Alex Ross 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
export class VerifiedTask {
	readonly task: Task;
	readonly resolver: ITaskResolver;
	readonly trigger: string;
	resolvedVariables?: ResolvedVariables;
	systemInfo?: TaskSystemInfo;
	workspaceFolder?: IWorkspaceFolder;
	shellLaunchConfig?: IShellLaunchConfig;

	constructor(task: Task, resolver: ITaskResolver, trigger: string) {
		this.task = task;
		this.resolver = resolver;
		this.trigger = trigger;
	}

	public verify(): boolean {
95 96 97 98 99
		let verified = false;
		if (this.trigger && this.resolvedVariables && this.workspaceFolder && (this.shellLaunchConfig !== undefined)) {
			verified = true;
		}
		return verified;
A
Alex Ross 已提交
100 101 102 103
	}

	public getVerifiedTask(): { task: Task, resolver: ITaskResolver, trigger: string, resolvedVariables: ResolvedVariables, systemInfo: TaskSystemInfo, workspaceFolder: IWorkspaceFolder, shellLaunchConfig: IShellLaunchConfig } {
		if (this.verify()) {
104
			return { task: this.task, resolver: this.resolver, trigger: this.trigger, resolvedVariables: this.resolvedVariables!, systemInfo: this.systemInfo!, workspaceFolder: this.workspaceFolder!, shellLaunchConfig: this.shellLaunchConfig! };
A
Alex Ross 已提交
105 106 107 108 109 110
		} else {
			throw new Error('VerifiedTask was not checked. verify must be checked before getVerifiedTask.');
		}
	}
}

111
export class TerminalTaskSystem implements ITaskSystem {
112 113 114

	public static TelemetryEventName: string = 'taskService';

A
Alex Ross 已提交
115
	private static ProcessVarName = '__process__';
116

117 118 119 120 121 122 123
	private static shellQuotes: IStringDictionary<ShellQuotingOptions> = {
		'cmd': {
			strong: '"'
		},
		'powershell': {
			escape: {
				escapeChar: '`',
124
				charsToEscape: ' "\'()'
125 126 127 128 129
			},
			strong: '\'',
			weak: '"'
		},
		'bash': {
130 131 132 133
			escape: {
				escapeChar: '\\',
				charsToEscape: ' "\''
			},
134 135 136 137
			strong: '\'',
			weak: '"'
		},
		'zsh': {
138 139 140 141
			escape: {
				escapeChar: '\\',
				charsToEscape: ' "\''
			},
142 143 144 145 146 147 148 149 150 151 152
			strong: '\'',
			weak: '"'
		}
	};

	private static osShellQuotes: IStringDictionary<ShellQuotingOptions> = {
		'linux': TerminalTaskSystem.shellQuotes['bash'],
		'darwin': TerminalTaskSystem.shellQuotes['bash'],
		'win32': TerminalTaskSystem.shellQuotes['powershell']
	};

D
Dirk Baeumer 已提交
153 154
	private activeTasks: IStringDictionary<ActiveTerminalData>;
	private terminals: IStringDictionary<TerminalData>;
155 156
	private idleTaskTerminals: LinkedMap<string, string>;
	private sameTaskTerminals: IStringDictionary<string>;
A
Alex Ross 已提交
157
	private taskSystemInfoResolver: TaskSystemInfoResolver;
A
Alex Ross 已提交
158 159 160
	private lastTask: VerifiedTask;
	private currentTask: VerifiedTask;
	private isRerun: boolean;
161

M
Matt Bierner 已提交
162
	private readonly _onDidStateChange: Emitter<TaskEvent>;
163

164 165 166
	constructor(
		private terminalService: ITerminalService,
		private outputService: IOutputService,
167
		private panelService: IPanelService,
168 169 170
		private markerService: IMarkerService, private modelService: IModelService,
		private configurationResolverService: IConfigurationResolverService,
		private telemetryService: ITelemetryService,
171
		private contextService: IWorkspaceContextService,
172
		private environmentService: IWorkbenchEnvironmentService,
173
		private outputChannelId: string,
174
		private fileService: IFileService,
175
		private terminalInstanceService: ITerminalInstanceService,
A
Alex Ross 已提交
176
		private remoteAgentService: IRemoteAgentService,
A
Alex Ross 已提交
177
		taskSystemInfoResolver: TaskSystemInfoResolver,
178
	) {
179 180

		this.activeTasks = Object.create(null);
D
Dirk Baeumer 已提交
181
		this.terminals = Object.create(null);
182 183
		this.idleTaskTerminals = new LinkedMap<string, string>();
		this.sameTaskTerminals = Object.create(null);
184 185

		this._onDidStateChange = new Emitter();
186
		this.taskSystemInfoResolver = taskSystemInfoResolver;
187 188 189 190
	}

	public get onDidStateChange(): Event<TaskEvent> {
		return this._onDidStateChange.event;
191 192 193
	}

	public log(value: string): void {
194
		this.appendOutput(value + '\n');
195 196
	}

197
	protected showOutput(): void {
198
		this.outputService.showChannel(this.outputChannelId, true);
199 200
	}

201
	public run(task: Task, resolver: ITaskResolver, trigger: string = Triggers.command): ITaskExecuteResult {
A
Alex Ross 已提交
202
		this.currentTask = new VerifiedTask(task, resolver, trigger);
A
Alex Ross 已提交
203
		let terminalData = this.activeTasks[task.getMapKey()];
D
Dirk Baeumer 已提交
204
		if (terminalData && terminalData.promise) {
205 206 207
			let reveal = RevealKind.Always;
			let focus = false;
			if (CustomTask.is(task) || ContributedTask.is(task)) {
208 209
				reveal = task.command.presentation!.reveal;
				focus = task.command.presentation!.focus;
210
			}
211 212 213
			if (reveal === RevealKind.Always || focus) {
				this.terminalService.setActiveInstance(terminalData.terminal);
				this.terminalService.showPanel(focus);
D
Dirk Baeumer 已提交
214
			}
A
Alex Ross 已提交
215
			this.lastTask = this.currentTask;
216
			return { kind: TaskExecuteKind.Active, task, active: { same: true, background: task.configurationProperties.isBackground! }, promise: terminalData.promise };
D
Dirk Baeumer 已提交
217 218
		}

219
		try {
A
Alex Ross 已提交
220
			const executeResult = { kind: TaskExecuteKind.Started, task, started: {}, promise: this.executeTask(task, resolver, trigger) };
221 222 223
			executeResult.promise.then(summary => {
				this.lastTask = this.currentTask;
			});
A
Alex Ross 已提交
224
			return executeResult;
225 226 227 228 229 230 231 232 233 234 235 236 237
		} catch (error) {
			if (error instanceof TaskError) {
				throw error;
			} else if (error instanceof Error) {
				this.log(error.message);
				throw new TaskError(Severity.Error, error.message, TaskErrors.UnknownError);
			} else {
				this.log(error.toString());
				throw new TaskError(Severity.Error, nls.localize('TerminalTaskSystem.unknownError', 'A unknown error has occurred while executing a task. See task output log for details.'), TaskErrors.UnknownError);
			}
		}
	}

A
Alex Ross 已提交
238 239
	public rerun(): ITaskExecuteResult | undefined {
		if (this.lastTask && this.lastTask.verify()) {
R
Rob Lourens 已提交
240
			if ((this.lastTask.task.runOptions.reevaluateOnRerun !== undefined) && !this.lastTask.task.runOptions.reevaluateOnRerun) {
A
Alex Ross 已提交
241 242 243
				this.isRerun = true;
			}
			const result = this.run(this.lastTask.task, this.lastTask.resolver);
244 245 246
			result.promise.then(summary => {
				this.isRerun = false;
			});
A
Alex Ross 已提交
247 248 249 250 251
			return result;
		} else {
			return undefined;
		}
	}
252 253

	public revealTask(task: Task): boolean {
A
Alex Ross 已提交
254
		let terminalData = this.activeTasks[task.getMapKey()];
255 256 257 258
		if (!terminalData) {
			return false;
		}
		this.terminalService.setActiveInstance(terminalData.terminal);
259
		if (CustomTask.is(task) || ContributedTask.is(task)) {
260
			this.terminalService.showPanel(task.command.presentation!.focus);
261
		}
262 263 264
		return true;
	}

265 266
	public isActive(): Promise<boolean> {
		return Promise.resolve(this.isActiveSync());
267 268 269
	}

	public isActiveSync(): boolean {
D
Dirk Baeumer 已提交
270
		return Object.keys(this.activeTasks).length > 0;
271 272 273
	}

	public canAutoTerminate(): boolean {
A
Alex Ross 已提交
274
		return Object.keys(this.activeTasks).every(key => !this.activeTasks[key].task.configurationProperties.promptOnClose);
275 276
	}

277 278 279 280
	public getActiveTasks(): Task[] {
		return Object.keys(this.activeTasks).map(key => this.activeTasks[key].task);
	}

G
Gabriel DeBacker 已提交
281
	public customExecutionComplete(task: Task, result: number): Promise<void> {
282 283
		let activeTerminal = this.activeTasks[task.getMapKey()];
		if (!activeTerminal) {
284
			return Promise.reject(new Error('Expected to have a terminal for an custom execution task'));
285 286 287
		}

		return new Promise<void>((resolve) => {
288
			activeTerminal.terminal.rendererExit(result);
289 290 291 292
			resolve();
		});
	}

293
	public terminate(task: Task): Promise<TaskTerminateResponse> {
A
Alex Ross 已提交
294
		let activeTerminal = this.activeTasks[task.getMapKey()];
295
		if (!activeTerminal) {
296
			return Promise.resolve<TaskTerminateResponse>({ success: false, task: undefined });
297
		}
298
		return new Promise<TaskTerminateResponse>((resolve, reject) => {
299
			let terminal = activeTerminal.terminal;
300

301
			const onExit = terminal.onExit(() => {
302 303 304
				let task = activeTerminal.task;
				try {
					onExit.dispose();
305
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Terminated, task));
306 307 308 309
				} catch (error) {
					// Do nothing.
				}
				resolve({ success: true, task: task });
310 311 312
			});
			terminal.dispose();
		});
313 314
	}

315 316
	public terminateAll(): Promise<TaskTerminateResponse[]> {
		let promises: Promise<TaskTerminateResponse>[] = [];
D
Dirk Baeumer 已提交
317
		Object.keys(this.activeTasks).forEach((key) => {
318 319
			let terminalData = this.activeTasks[key];
			let terminal = terminalData.terminal;
320
			promises.push(new Promise<TaskTerminateResponse>((resolve, reject) => {
321 322 323 324
				const onExit = terminal.onExit(() => {
					let task = terminalData.task;
					try {
						onExit.dispose();
325
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Terminated, task));
326 327 328 329 330 331 332
					} catch (error) {
						// Do nothing.
					}
					resolve({ success: true, task: terminalData.task });
				});
			}));
			terminal.dispose();
D
Dirk Baeumer 已提交
333 334
		});
		this.activeTasks = Object.create(null);
335
		return Promise.all<TaskTerminateResponse>(promises);
336 337
	}

338
	private async executeTask(task: Task, resolver: ITaskResolver, trigger: string): Promise<ITaskSummary> {
339
		let promises: Promise<ITaskSummary>[] = [];
A
Alex Ross 已提交
340
		if (task.configurationProperties.dependsOn) {
341 342
			for (let index in task.configurationProperties.dependsOn) {
				const dependency = task.configurationProperties.dependsOn[index];
343 344 345
				let dependencyTask = resolver.resolve(dependency.workspaceFolder, dependency.task!);
				if (dependencyTask) {
					let key = dependencyTask.getMapKey();
346
					let promise = this.activeTasks[key] ? this.activeTasks[key].promise : undefined;
D
Dirk Baeumer 已提交
347
					if (!promise) {
348 349
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.DependsOnStarted, task));
						promise = this.executeTask(dependencyTask, resolver, trigger);
D
Dirk Baeumer 已提交
350
					}
351 352 353
					if (task.configurationProperties.dependsOrder === DependsOrder.sequence) {
						promise = Promise.resolve(await promise);
					}
D
Dirk Baeumer 已提交
354
					promises.push(promise);
355
				} else {
356 357 358 359 360
					this.log(nls.localize('dependencyFailed',
						'Couldn\'t resolve dependent task \'{0}\' in workspace folder \'{1}\'',
						Types.isString(dependency.task) ? dependency.task : JSON.stringify(dependency.task, undefined, 0),
						dependency.workspaceFolder.name
					));
361
					this.showOutput();
D
Dirk Baeumer 已提交
362
				}
363
			}
D
Dirk Baeumer 已提交
364 365
		}

366
		if ((ContributedTask.is(task) || CustomTask.is(task)) && (task.command)) {
367
			return Promise.all(promises).then((summaries): Promise<ITaskSummary> | ITaskSummary => {
D
Dirk Baeumer 已提交
368 369 370 371 372
				for (let summary of summaries) {
					if (summary.exitCode !== 0) {
						return { exitCode: summary.exitCode };
					}
				}
A
Alex Ross 已提交
373 374 375 376 377
				if (this.isRerun) {
					return this.reexecuteCommand(task, trigger);
				} else {
					return this.executeCommand(task, trigger);
				}
D
Dirk Baeumer 已提交
378
			});
379
		} else {
380
			return Promise.all(promises).then((summaries): ITaskSummary => {
D
Dirk Baeumer 已提交
381 382 383 384 385 386 387 388 389 390
				for (let summary of summaries) {
					if (summary.exitCode !== 0) {
						return { exitCode: summary.exitCode };
					}
				}
				return { exitCode: 0 };
			});
		}
	}

391
	private resolveVariablesFromSet(taskSystemInfo: TaskSystemInfo | undefined, workspaceFolder: IWorkspaceFolder, task: CustomTask | ContributedTask, variables: Set<string>): Promise<ResolvedVariables> {
392 393 394 395 396 397 398 399 400 401 402 403 404 405
		let isProcess = task.command && task.command.runtime === RuntimeType.Process;
		let options = task.command && task.command.options ? task.command.options : undefined;
		let cwd = options ? options.cwd : undefined;
		let envPath: string | undefined = undefined;
		if (options && options.env) {
			for (let key of Object.keys(options.env)) {
				if (key.toLowerCase() === 'path') {
					if (Types.isString(options.env[key])) {
						envPath = options.env[key];
					}
					break;
				}
			}
		}
A
Alex Ross 已提交
406

407
		let resolvedVariables: Promise<ResolvedVariables>;
408
		if (taskSystemInfo) {
409 410 411
			let resolveSet: ResolveSet = {
				variables
			};
A
Alex Ross 已提交
412

413
			if (taskSystemInfo.platform === Platform.Platform.Windows && isProcess) {
414
				resolveSet.process = { name: CommandString.value(task.command.name!) };
415 416 417 418 419 420 421
				if (cwd) {
					resolveSet.process.cwd = cwd;
				}
				if (envPath) {
					resolveSet.process.path = envPath;
				}
			}
A
Alex Ross 已提交
422 423
			resolvedVariables = taskSystemInfo.resolveVariables(workspaceFolder, resolveSet).then(resolved => {
				if ((taskSystemInfo.platform !== Platform.Platform.Windows) && isProcess) {
424
					resolved.variables.set(TerminalTaskSystem.ProcessVarName, CommandString.value(task.command.name!));
A
Alex Ross 已提交
425 426 427
				}
				return Promise.resolve(resolved);
			});
A
Alex Ross 已提交
428
			return resolvedVariables;
429
		} else {
A
Alex Ross 已提交
430 431 432 433
			let variablesArray = new Array<string>();
			variables.forEach(variable => variablesArray.push(variable));

			return new Promise((resolve, reject) => {
A
Alex Ross 已提交
434
				this.configurationResolverService.resolveWithInteraction(workspaceFolder, variablesArray, 'tasks').then(async resolvedVariablesMap => {
435 436 437 438
					if (resolvedVariablesMap) {
						if (isProcess) {
							let processVarValue: string;
							if (Platform.isWindows) {
439
								processVarValue = await this.findExecutable(
440
									this.configurationResolverService.resolve(workspaceFolder, CommandString.value(task.command.name!)),
441 442 443 444
									cwd ? this.configurationResolverService.resolve(workspaceFolder, cwd) : undefined,
									envPath ? envPath.split(path.delimiter).map(p => this.configurationResolverService.resolve(workspaceFolder, p)) : undefined
								);
							} else {
445
								processVarValue = this.configurationResolverService.resolve(workspaceFolder, CommandString.value(task.command.name!));
446 447
							}
							resolvedVariablesMap.set(TerminalTaskSystem.ProcessVarName, processVarValue);
A
Alex Ross 已提交
448
						}
449 450 451 452 453 454
						let resolvedVariablesResult: ResolvedVariables = {
							variables: resolvedVariablesMap,
						};
						resolve(resolvedVariablesResult);
					} else {
						resolve(undefined);
A
Alex Ross 已提交
455 456 457 458
					}
				}, reason => {
					reject(reason);
				});
459 460
			});
		}
A
Alex Ross 已提交
461 462
	}

463
	private executeCommand(task: CustomTask | ContributedTask, trigger: string): Promise<ITaskSummary> {
A
Alex Ross 已提交
464
		this.currentTask.workspaceFolder = task.getWorkspaceFolder();
A
Alex Ross 已提交
465 466 467 468 469 470
		if (this.currentTask.workspaceFolder) {
			this.currentTask.systemInfo = this.taskSystemInfoResolver(this.currentTask.workspaceFolder);
		}

		let variables = new Set<string>();
		this.collectTaskVariables(variables, task);
471
		const resolvedVariables = this.resolveVariablesFromSet(this.currentTask.systemInfo, this.currentTask.workspaceFolder!, task, variables);
A
Alex Ross 已提交
472 473

		return resolvedVariables.then((resolvedVariables) => {
474
			if (resolvedVariables && task.command && task.command.runtime) {
475
				this.currentTask.resolvedVariables = resolvedVariables;
476
				return this.executeInTerminal(task, trigger, new VariableResolver(this.currentTask.workspaceFolder!, this.currentTask.systemInfo, resolvedVariables.variables, this.configurationResolverService));
477 478 479
			} else {
				return Promise.resolve({ exitCode: 0 });
			}
A
Alex Ross 已提交
480 481
		}, reason => {
			return Promise.reject(reason);
482 483 484
		});
	}

485
	private reexecuteCommand(task: CustomTask | ContributedTask, trigger: string): Promise<ITaskSummary> {
A
Alex Ross 已提交
486 487 488 489 490 491 492
		this.currentTask.workspaceFolder = this.lastTask.workspaceFolder;
		let variables = new Set<string>();
		this.collectTaskVariables(variables, task);

		// Check that the task hasn't changed to include new variables
		let hasAllVariables = true;
		variables.forEach(value => {
493
			if (value.substring(2, value.length - 1) in this.lastTask.getVerifiedTask().resolvedVariables) {
A
Alex Ross 已提交
494 495 496 497 498 499 500 501
				hasAllVariables = false;
			}
		});

		if (!hasAllVariables) {
			return this.resolveVariablesFromSet(this.lastTask.getVerifiedTask().systemInfo, this.lastTask.getVerifiedTask().workspaceFolder, task, variables).then((resolvedVariables) => {
				this.currentTask.resolvedVariables = resolvedVariables;
				return this.executeInTerminal(task, trigger, new VariableResolver(this.lastTask.getVerifiedTask().workspaceFolder, this.lastTask.getVerifiedTask().systemInfo, resolvedVariables.variables, this.configurationResolverService));
A
Alex Ross 已提交
502 503
			}, reason => {
				return Promise.reject(reason);
A
Alex Ross 已提交
504 505 506 507 508 509 510
			});
		} else {
			this.currentTask.resolvedVariables = this.lastTask.getVerifiedTask().resolvedVariables;
			return this.executeInTerminal(task, trigger, new VariableResolver(this.lastTask.getVerifiedTask().workspaceFolder, this.lastTask.getVerifiedTask().systemInfo, this.lastTask.getVerifiedTask().resolvedVariables.variables, this.configurationResolverService));
		}
	}

A
Alex Ross 已提交
511
	private async executeInTerminal(task: CustomTask | ContributedTask, trigger: string, resolver: VariableResolver): Promise<ITaskSummary> {
512 513 514
		let terminal: ITerminalInstance | undefined = undefined;
		let executedCommand: string | undefined = undefined;
		let error: TaskError | undefined = undefined;
515
		let promise: Promise<ITaskSummary> | undefined = undefined;
A
Alex Ross 已提交
516
		if (task.configurationProperties.isBackground) {
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
			const problemMatchers = this.resolveMatchers(resolver, task.configurationProperties.problemMatchers);
			let watchingProblemMatcher = new WatchingProblemCollector(problemMatchers, this.markerService, this.modelService, this.fileService);
			let toDispose: IDisposable[] | undefined = [];
			let eventCounter: number = 0;
			toDispose.push(watchingProblemMatcher.onDidStateChange((event) => {
				if (event.kind === ProblemCollectorEventKind.BackgroundProcessingBegins) {
					eventCounter++;
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Active, task));
				} else if (event.kind === ProblemCollectorEventKind.BackgroundProcessingEnds) {
					eventCounter--;
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Inactive, task));
					if (eventCounter === 0) {
						if ((watchingProblemMatcher.numberOfMatches > 0) && watchingProblemMatcher.maxMarkerSeverity &&
							(watchingProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error)) {
							let reveal = task.command.presentation!.reveal;
							let revealProblems = task.command.presentation!.revealProblems;
							if (revealProblems === RevealProblemKind.OnProblem) {
								this.panelService.openPanel(Constants.MARKERS_PANEL_ID, true);
							} else if (reveal === RevealKind.Silent) {
								this.terminalService.setActiveInstance(terminal!);
								this.terminalService.showPanel(false);
538 539
							}
						}
540
					}
541
				}
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
			}));
			watchingProblemMatcher.aboutToStart();
			let delayer: Async.Delayer<any> | undefined = undefined;
			[terminal, executedCommand, error] = await this.createTerminal(task, resolver);

			if (error) {
				return Promise.reject(new Error((<TaskError>error).message));
			}
			if (!terminal) {
				return Promise.reject(new Error(`Failed to create terminal for task ${task._label}`));
			}

			let processStartedSignaled = false;
			terminal.processReady.then(() => {
				if (!processStartedSignaled) {
					if (task.command.runtime !== RuntimeType.CustomExecution) {
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
559
					}
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
					processStartedSignaled = true;
				}
			}, (_error) => {
				// The process never got ready. Need to think how to handle this.
			});
			this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Start, task, terminal.id));
			const registeredLinkMatchers = this.registerLinkMatchers(terminal, problemMatchers);
			const onData = terminal.onLineData((line) => {
				watchingProblemMatcher.processLine(line);
				if (!delayer) {
					delayer = new Async.Delayer(3000);
				}
				delayer.trigger(() => {
					watchingProblemMatcher.forceDelivery();
					delayer = undefined;
D
Dirk Baeumer 已提交
575
				});
576 577 578
			});
			promise = new Promise<ITaskSummary>((resolve, reject) => {
				const onExit = terminal!.onExit((exitCode) => {
D
Dirk Baeumer 已提交
579 580
					onData.dispose();
					onExit.dispose();
A
Alex Ross 已提交
581
					let key = task.getMapKey();
582
					delete this.activeTasks[key];
583
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Changed));
584 585 586 587 588 589 590 591 592 593
					if (exitCode !== undefined) {
						// Only keep a reference to the terminal if it is not being disposed.
						switch (task.command.presentation!.panel) {
							case PanelKind.Dedicated:
								this.sameTaskTerminals[key] = terminal!.id.toString();
								break;
							case PanelKind.Shared:
								this.idleTaskTerminals.set(key, terminal!.id.toString(), Touch.AsOld);
								break;
						}
D
Dirk Baeumer 已提交
594
					}
595 596 597 598
					let reveal = task.command.presentation!.reveal;
					if ((reveal === RevealKind.Silent) && ((exitCode !== 0) || (watchingProblemMatcher.numberOfMatches > 0) && watchingProblemMatcher.maxMarkerSeverity &&
						(watchingProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error))) {
						this.terminalService.setActiveInstance(terminal!);
599 600
						this.terminalService.showPanel(false);
					}
D
Dirk Baeumer 已提交
601
					watchingProblemMatcher.done();
D
Dirk Baeumer 已提交
602
					watchingProblemMatcher.dispose();
603
					registeredLinkMatchers.forEach(handle => terminal!.deregisterLinkMatcher(handle));
604
					if (!processStartedSignaled) {
605
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
606
						processStartedSignaled = true;
607
					}
G
Gabriel DeBacker 已提交
608 609 610 611 612

					if (task.command.runtime !== RuntimeType.CustomExecution) {
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, exitCode));
					}

D
Dirk Baeumer 已提交
613
					for (let i = 0; i < eventCounter; i++) {
614 615
						let event = TaskEvent.create(TaskEventKind.Inactive, task);
						this._onDidStateChange.fire(event);
D
Dirk Baeumer 已提交
616 617
					}
					eventCounter = 0;
618
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
619 620
					toDispose = dispose(toDispose!);
					toDispose = undefined;
D
Dirk Baeumer 已提交
621 622 623 624
					resolve({ exitCode });
				});
			});
		} else {
625
			[terminal, executedCommand, error] = await this.createTerminal(task, resolver);
626

627 628 629 630 631 632 633 634 635 636 637 638
			if (error) {
				return Promise.reject(new Error((<TaskError>error).message));
			}
			if (!terminal) {
				return Promise.reject(new Error(`Failed to create terminal for task ${task._label}`));
			}

			let processStartedSignaled = false;
			terminal.processReady.then(() => {
				if (!processStartedSignaled) {
					if (task.command.runtime !== RuntimeType.CustomExecution) {
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
639
					}
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
					processStartedSignaled = true;
				}
			}, (_error) => {
				// The process never got ready. Need to think how to handle this.
			});
			this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Start, task, terminal.id));
			this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Active, task));
			let problemMatchers = this.resolveMatchers(resolver, task.configurationProperties.problemMatchers);
			let startStopProblemMatcher = new StartStopProblemCollector(problemMatchers, this.markerService, this.modelService, ProblemHandlingStrategy.Clean, this.fileService);
			const registeredLinkMatchers = this.registerLinkMatchers(terminal, problemMatchers);
			const onData = terminal.onLineData((line) => {
				startStopProblemMatcher.processLine(line);
			});
			promise = new Promise<ITaskSummary>((resolve, reject) => {
				const onExit = terminal!.onExit((exitCode) => {
D
Dirk Baeumer 已提交
655 656
					onData.dispose();
					onExit.dispose();
A
Alex Ross 已提交
657
					let key = task.getMapKey();
658
					delete this.activeTasks[key];
659
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Changed));
660 661 662 663 664 665 666 667 668 669
					if (exitCode !== undefined) {
						// Only keep a reference to the terminal if it is not being disposed.
						switch (task.command.presentation!.panel) {
							case PanelKind.Dedicated:
								this.sameTaskTerminals[key] = terminal!.id.toString();
								break;
							case PanelKind.Shared:
								this.idleTaskTerminals.set(key, terminal!.id.toString(), Touch.AsOld);
								break;
						}
D
Dirk Baeumer 已提交
670
					}
671
					let reveal = task.command.presentation!.reveal;
672 673
					let revealProblems = task.command.presentation!.revealProblems;
					let revealProblemPanel = terminal && (revealProblems === RevealProblemKind.OnProblem) && (startStopProblemMatcher.numberOfMatches > 0);
674 675 676
					if (revealProblemPanel) {
						this.panelService.openPanel(Constants.MARKERS_PANEL_ID);
					} else if (terminal && (reveal === RevealKind.Silent) && ((exitCode !== 0) || (startStopProblemMatcher.numberOfMatches > 0) && startStopProblemMatcher.maxMarkerSeverity &&
677
						(startStopProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error))) {
678 679 680
						this.terminalService.setActiveInstance(terminal);
						this.terminalService.showPanel(false);
					}
D
Dirk Baeumer 已提交
681 682
					startStopProblemMatcher.done();
					startStopProblemMatcher.dispose();
683 684 685 686 687 688 689
					registeredLinkMatchers.forEach(handle => {
						if (terminal) {
							terminal.deregisterLinkMatcher(handle);
						}
					});
					if (!processStartedSignaled && terminal) {
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal.processId!));
690
						processStartedSignaled = true;
691
					}
G
Gabriel DeBacker 已提交
692 693 694
					if (task.command.runtime !== RuntimeType.CustomExecution) {
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, exitCode));
					}
695
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Inactive, task));
696
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
D
Dirk Baeumer 已提交
697 698 699 700
					resolve({ exitCode });
				});
			});
		}
701

702
		let showProblemPanel = task.command.presentation && (task.command.presentation.revealProblems === RevealProblemKind.Always);
703 704 705
		if (showProblemPanel) {
			this.panelService.openPanel(Constants.MARKERS_PANEL_ID);
		} else if (task.command.presentation && (task.command.presentation.reveal === RevealKind.Always)) {
706
			this.terminalService.setActiveInstance(terminal);
707
			this.terminalService.showPanel(task.command.presentation.focus);
D
Dirk Baeumer 已提交
708
		}
A
Alex Ross 已提交
709
		this.activeTasks[task.getMapKey()] = { terminal, task, promise };
710
		this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Changed));
D
Dirk Baeumer 已提交
711 712 713 714
		return promise.then((summary) => {
			try {
				let telemetryEvent: TelemetryEvent = {
					trigger: trigger,
715
					runner: 'terminal',
A
Alex Ross 已提交
716
					taskKind: task.getTelemetryKind(),
717
					command: this.getSanitizedCommand(executedCommand!),
D
Dirk Baeumer 已提交
718 719 720
					success: true,
					exitCode: summary.exitCode
				};
K
kieferrm 已提交
721
				/* __GDPR__
K
kieferrm 已提交
722 723 724 725
					"taskService" : {
						"${include}": [
							"${TelemetryEvent}"
						]
K
kieferrm 已提交
726
					}
K
kieferrm 已提交
727
				*/
D
Dirk Baeumer 已提交
728 729
				this.telemetryService.publicLog(TerminalTaskSystem.TelemetryEventName, telemetryEvent);
			} catch (error) {
730
			}
D
Dirk Baeumer 已提交
731 732 733 734 735
			return summary;
		}, (error) => {
			try {
				let telemetryEvent: TelemetryEvent = {
					trigger: trigger,
736
					runner: 'terminal',
A
Alex Ross 已提交
737
					taskKind: task.getTelemetryKind(),
738
					command: this.getSanitizedCommand(executedCommand!),
D
Dirk Baeumer 已提交
739 740
					success: false
				};
K
kieferrm 已提交
741
				/* __GDPR__
K
kieferrm 已提交
742 743 744 745 746 747
					"taskService" : {
						"${include}": [
							"${TelemetryEvent}"
						]
					}
				*/
D
Dirk Baeumer 已提交
748 749
				this.telemetryService.publicLog(TerminalTaskSystem.TelemetryEventName, telemetryEvent);
			} catch (error) {
750
			}
751
			return Promise.reject<ITaskSummary>(error);
D
Dirk Baeumer 已提交
752
		});
753 754
	}

755 756 757 758 759
	private createTerminalName(task: CustomTask | ContributedTask): string {
		const needsFolderQualification = this.currentTask.workspaceFolder && this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE;
		return nls.localize('TerminalTaskSystem.terminalName', 'Task - {0}', needsFolderQualification ? task.getQualifiedLabel() : task.configurationProperties.name);
	}

A
Alex Ross 已提交
760 761 762 763 764 765 766 767 768
	private async getUserHome(): Promise<URI> {
		const env = await this.remoteAgentService.getEnvironment();
		if (env) {
			return env.userHome;
		}
		return URI.from({ scheme: Schemas.file, path: this.environmentService.userHome });
	}

	private async createShellLaunchConfig(task: CustomTask | ContributedTask, variableResolver: VariableResolver, platform: Platform.Platform, options: CommandOptions, command: CommandString, args: CommandString[], waitOnExit: boolean | string): Promise<IShellLaunchConfig | undefined> {
769
		let shellLaunchConfig: IShellLaunchConfig;
770
		let isShellCommand = task.command.runtime === RuntimeType.Shell;
A
Alex Ross 已提交
771
		let needsFolderQualification = this.currentTask.workspaceFolder && this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE;
772
		let terminalName = this.createTerminalName(task);
A
Alex Ross 已提交
773
		let originalCommand = task.command.name;
D
Dirk Baeumer 已提交
774
		if (isShellCommand) {
775
			const defaultConfig = await this.terminalInstanceService.getDefaultShellAndArgs(platform);
D
Daniel Imms 已提交
776
			shellLaunchConfig = { name: terminalName, executable: defaultConfig.shell, args: defaultConfig.args, waitOnExit };
777
			let shellSpecified: boolean = false;
778
			let shellOptions: ShellConfiguration | undefined = task.command.options && task.command.options.shell;
779 780
			if (shellOptions) {
				if (shellOptions.executable) {
A
Alex Ross 已提交
781
					shellLaunchConfig.executable = this.resolveVariable(variableResolver, shellOptions.executable);
782 783
					shellSpecified = true;
				}
D
Dirk Baeumer 已提交
784
				if (shellOptions.args) {
A
Alex Ross 已提交
785
					shellLaunchConfig.args = this.resolveVariables(variableResolver, shellOptions.args.slice());
786
				} else {
787
					shellLaunchConfig.args = [];
788 789
				}
			}
790
			let shellArgs = <string[]>shellLaunchConfig.args!.slice(0);
791
			let toAdd: string[] = [];
792
			let commandLine = this.buildShellCommandLine(platform, shellLaunchConfig.executable!, shellOptions, command, originalCommand, args);
793
			let windowsShellArgs: boolean = false;
794
			if (platform === Platform.Platform.Windows) {
795
				windowsShellArgs = true;
796
				let basename = path.basename(shellLaunchConfig.executable!).toLowerCase();
A
Alex Ross 已提交
797 798 799
				// If we don't have a cwd, then the terminal uses the home dir.
				const userHome = await this.getUserHome();
				if (basename === 'cmd.exe' && ((options.cwd && isUNC(options.cwd)) || (!options.cwd && isUNC(userHome.fsPath)))) {
A
Alex Ross 已提交
800
					return undefined;
801
				}
A
Alex Ross 已提交
802
				if ((basename === 'powershell.exe') || (basename === 'pwsh.exe')) {
803 804 805
					if (!shellSpecified) {
						toAdd.push('-Command');
					}
806
				} else if ((basename === 'bash.exe') || (basename === 'zsh.exe')) {
807
					windowsShellArgs = false;
808 809 810
					if (!shellSpecified) {
						toAdd.push('-c');
					}
A
Alex Ross 已提交
811
				} else if (basename === 'wsl.exe') {
812
					if (!shellSpecified) {
A
Alex Ross 已提交
813 814
						toAdd.push('-e');
					}
815
				} else {
816 817 818
					if (!shellSpecified) {
						toAdd.push('/d', '/c');
					}
819 820
				}
			} else {
821
				if (!shellSpecified) {
D
Dirk Baeumer 已提交
822
					// Under Mac remove -l to not start it as a login shell.
823
					if (platform === Platform.Platform.Mac) {
D
Dirk Baeumer 已提交
824 825 826 827 828
						let index = shellArgs.indexOf('-l');
						if (index !== -1) {
							shellArgs.splice(index, 1);
						}
					}
829 830
					toAdd.push('-c');
				}
831 832 833 834 835 836 837
			}
			toAdd.forEach(element => {
				if (!shellArgs.some(arg => arg.toLowerCase() === element)) {
					shellArgs.push(element);
				}
			});
			shellArgs.push(commandLine);
838
			shellLaunchConfig.args = windowsShellArgs ? shellArgs.join(' ') : shellArgs;
839
			if (task.command.presentation && task.command.presentation.echo) {
840
				if (needsFolderQualification) {
841
					shellLaunchConfig.initialText = `\x1b[1m> Executing task in folder ${this.currentTask.workspaceFolder!.name}: ${commandLine} <\x1b[0m\n`;
842 843 844
				} else {
					shellLaunchConfig.initialText = `\x1b[1m> Executing task: ${commandLine} <\x1b[0m\n`;
				}
D
Dirk Baeumer 已提交
845
			}
846
		} else {
G
Gabriel DeBacker 已提交
847
			let commandExecutable = task.command.runtime !== RuntimeType.CustomExecution ? CommandString.value(command) : undefined;
848
			let executable = !isShellCommand
A
Alex Ross 已提交
849
				? this.resolveVariable(variableResolver, '${' + TerminalTaskSystem.ProcessVarName + '}')
850
				: commandExecutable;
851 852

			// When we have a process task there is no need to quote arguments. So we go ahead and take the string value.
D
Dirk Baeumer 已提交
853
			shellLaunchConfig = {
854
				name: terminalName,
855
				executable: executable,
856
				args: args.map(a => Types.isString(a) ? a : a.value),
857 858
				waitOnExit
			};
859 860
			if (task.command.presentation && task.command.presentation.echo) {
				let getArgsToEcho = (args: string | string[] | undefined): string => {
D
Dirk Baeumer 已提交
861 862 863 864 865 866 867 868
					if (!args || args.length === 0) {
						return '';
					}
					if (Types.isString(args)) {
						return args;
					}
					return args.join(' ');
				};
869
				if (needsFolderQualification) {
870
					shellLaunchConfig.initialText = `\x1b[1m> Executing task in folder ${this.currentTask.workspaceFolder!.name}: ${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)} <\x1b[0m\n`;
871 872 873
				} else {
					shellLaunchConfig.initialText = `\x1b[1m> Executing task: ${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)} <\x1b[0m\n`;
				}
D
Dirk Baeumer 已提交
874
			}
875
		}
A
Alex Ross 已提交
876

877
		if (options.cwd) {
878
			let cwd = options.cwd;
B
Benjamin Pasero 已提交
879
			if (!path.isAbsolute(cwd)) {
A
Alex Ross 已提交
880
				let workspaceFolder = task.getWorkspaceFolder();
881
				if (workspaceFolder && (workspaceFolder.uri.scheme === 'file')) {
B
Benjamin Pasero 已提交
882
					cwd = path.join(workspaceFolder.uri.fsPath, cwd);
883 884 885
				}
			}
			// This must be normalized to the OS
A
Alex Ross 已提交
886
			shellLaunchConfig.cwd = resources.toLocalResource(URI.from({ scheme: Schemas.file, path: cwd }), this.environmentService.configuration.remoteAuthority);
887 888
		}
		if (options.env) {
889
			shellLaunchConfig.env = options.env;
890
		}
A
Alex Ross 已提交
891 892 893
		return shellLaunchConfig;
	}

A
Alex Ross 已提交
894
	private async createTerminal(task: CustomTask | ContributedTask, resolver: VariableResolver): Promise<[ITerminalInstance | undefined, string | undefined, TaskError | undefined]> {
A
Alex Ross 已提交
895 896
		let platform = resolver.taskSystemInfo ? resolver.taskSystemInfo.platform : Platform.platform;
		let options = this.resolveOptions(resolver, task.command.options);
897

A
Alex Ross 已提交
898
		let waitOnExit: boolean | string = false;
899 900 901 902
		const presentationOptions = task.command.presentation;
		if (!presentationOptions) {
			throw new Error('Task presentation options should not be undefined here.');
		}
A
Alex Ross 已提交
903

904 905
		if (presentationOptions.reveal !== RevealKind.Never || !task.configurationProperties.isBackground) {
			if (presentationOptions.panel === PanelKind.New) {
A
Alex Ross 已提交
906
				waitOnExit = nls.localize('closeTerminal', 'Press any key to close the terminal.');
907
			} else if (presentationOptions.showReuseMessage) {
A
Alex Ross 已提交
908 909 910 911 912
				waitOnExit = nls.localize('reuseTerminal', 'Terminal will be reused by tasks, press any key to close it.');
			} else {
				waitOnExit = true;
			}
		}
913 914 915 916 917

		let commandExecutable: string | undefined;
		let command: CommandString | undefined;
		let args: CommandString[] | undefined;

G
Gabriel DeBacker 已提交
918
		if (task.command.runtime === RuntimeType.CustomExecution) {
919 920 921
			this.currentTask.shellLaunchConfig = {
				isRendererOnly: true,
				waitOnExit,
A
Alex Ross 已提交
922 923
				name: this.createTerminalName(task),
				initialText: task.command.presentation && task.command.presentation.echo ? `\x1b[1m> Executing task: ${task._label} <\x1b[0m\n` : undefined
924 925
			};
		} else {
926 927 928 929 930
			let resolvedResult: { command: CommandString, args: CommandString[] } = this.resolveCommandAndArgs(resolver, task.command);
			command = resolvedResult.command;
			args = resolvedResult.args;
			commandExecutable = CommandString.value(command);

A
Alex Ross 已提交
931
			this.currentTask.shellLaunchConfig = this.isRerun ? this.lastTask.getVerifiedTask().shellLaunchConfig : await this.createShellLaunchConfig(task, resolver, platform, options, command, args, waitOnExit);
932 933 934
			if (this.currentTask.shellLaunchConfig === undefined) {
				return [undefined, undefined, new TaskError(Severity.Error, nls.localize('TerminalTaskSystem', 'Can\'t execute a shell command on an UNC drive using cmd.exe.'), TaskErrors.UnknownError)];
			}
A
Alex Ross 已提交
935
		}
936

937 938
		let prefersSameTerminal = presentationOptions.panel === PanelKind.Dedicated;
		let allowsSharedTerminal = presentationOptions.panel === PanelKind.Shared;
939
		let group = presentationOptions.group;
940

A
Alex Ross 已提交
941
		let taskKey = task.getMapKey();
942
		let terminalToReuse: TerminalData | undefined;
943
		if (prefersSameTerminal) {
944
			let terminalId = this.sameTaskTerminals[taskKey];
945 946
			if (terminalId) {
				terminalToReuse = this.terminals[terminalId];
947
				delete this.sameTaskTerminals[taskKey];
D
Dirk Baeumer 已提交
948
			}
949
		} else if (allowsSharedTerminal) {
950 951 952 953 954 955 956 957
			// Always allow to reuse the terminal previously used by the same task.
			let terminalId = this.idleTaskTerminals.remove(taskKey);
			if (!terminalId) {
				// There is no idle terminal which was used by the same task.
				// Search for any idle terminal used previously by a task of the same group
				// (or, if the task has no group, a terminal used by a task without group).
				for (const taskId of this.idleTaskTerminals.keys()) {
					const idleTerminalId = this.idleTaskTerminals.get(taskId)!;
958
					if (idleTerminalId && this.terminals[idleTerminalId] && this.terminals[idleTerminalId].group === group) {
959 960 961 962 963
						terminalId = this.idleTaskTerminals.remove(taskId);
						break;
					}
				}
			}
964 965
			if (terminalId) {
				terminalToReuse = this.terminals[terminalId];
966
			}
D
Dirk Baeumer 已提交
967
		}
968
		if (terminalToReuse) {
969 970
			if (!this.currentTask.shellLaunchConfig) {
				throw new Error('Task shell launch configuration should not be undefined here.');
971 972
			}

973 974
			terminalToReuse.terminal.reuseTerminal(this.currentTask.shellLaunchConfig);

975
			if (task.command.presentation && task.command.presentation.clear) {
976 977
				terminalToReuse.terminal.clear();
			}
978
			this.terminals[terminalToReuse.terminal.id.toString()].lastTask = taskKey;
979
			return [terminalToReuse.terminal, commandExecutable, undefined];
980 981
		}

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
		let result: ITerminalInstance | null = null;
		if (group) {
			// Try to find an existing terminal to split.
			// Even if an existing terminal is found, the split can fail if the terminal width is too small.
			for (const terminal of values(this.terminals)) {
				if (terminal.group === group) {
					const originalInstance = terminal.terminal;
					const config = this.currentTask.shellLaunchConfig;
					result = this.terminalService.splitInstance(originalInstance, config);
					if (result) {
						break;
					}
				}
			}
		}
		if (!result) {
			// Either no group is used, no terminal with the group exists or splitting an existing terminal failed.
			result = this.terminalService.createTerminal(this.currentTask.shellLaunchConfig);
		}

1002
		const terminalKey = result.id.toString();
D
Dirk Baeumer 已提交
1003
		result.onDisposed((terminal) => {
1004
			let terminalData = this.terminals[terminalKey];
D
Dirk Baeumer 已提交
1005
			if (terminalData) {
1006
				delete this.terminals[terminalKey];
1007 1008
				delete this.sameTaskTerminals[terminalData.lastTask];
				this.idleTaskTerminals.delete(terminalData.lastTask);
1009 1010 1011 1012
				// Delete the task now as a work around for cases when the onExit isn't fired.
				// This can happen if the terminal wasn't shutdown with an "immediate" flag and is expected.
				// For correct terminal re-use, the task needs to be deleted immediately.
				// Note that this shouldn't be a problem anymore since user initiated terminal kills are now immediate.
A
Alex Ross 已提交
1013
				delete this.activeTasks[task.getMapKey()];
D
Dirk Baeumer 已提交
1014 1015
			}
		});
1016
		this.terminals[terminalKey] = { terminal: result, lastTask: taskKey, group };
1017
		return [result, commandExecutable, undefined];
1018 1019
	}

1020
	private buildShellCommandLine(platform: Platform.Platform, shellExecutable: string, shellOptions: ShellConfiguration | undefined, command: CommandString, originalCommand: CommandString | undefined, args: CommandString[]): string {
1021
		let basename = path.parse(shellExecutable).name.toLowerCase();
A
Alex Ross 已提交
1022
		let shellQuoteOptions = this.getQuotingOptions(basename, shellOptions, platform);
1023 1024 1025 1026 1027 1028 1029 1030

		function needsQuotes(value: string): boolean {
			if (value.length >= 2) {
				let first = value[0] === shellQuoteOptions.strong ? shellQuoteOptions.strong : value[0] === shellQuoteOptions.weak ? shellQuoteOptions.weak : undefined;
				if (first === value[value.length - 1]) {
					return false;
				}
			}
1031
			let quote: string | undefined;
1032
			for (let i = 0; i < value.length; i++) {
1033 1034 1035 1036
				// We found the end quote.
				let ch = value[i];
				if (ch === quote) {
					quote = undefined;
R
Rob Lourens 已提交
1037
				} else if (quote !== undefined) {
1038 1039 1040 1041 1042 1043 1044 1045
					// skip the character. We are quoted.
					continue;
				} else if (ch === shellQuoteOptions.escape) {
					// Skip the next character
					i++;
				} else if (ch === shellQuoteOptions.strong || ch === shellQuoteOptions.weak) {
					quote = ch;
				} else if (ch === ' ') {
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
					return true;
				}
			}
			return false;
		}

		function quote(value: string, kind: ShellQuoting): [string, boolean] {
			if (kind === ShellQuoting.Strong && shellQuoteOptions.strong) {
				return [shellQuoteOptions.strong + value + shellQuoteOptions.strong, true];
			} else if (kind === ShellQuoting.Weak && shellQuoteOptions.weak) {
				return [shellQuoteOptions.weak + value + shellQuoteOptions.weak, true];
			} else if (kind === ShellQuoting.Escape && shellQuoteOptions.escape) {
				if (Types.isString(shellQuoteOptions.escape)) {
					return [value.replace(/ /g, shellQuoteOptions.escape + ' '), true];
				} else {
					let buffer: string[] = [];
					for (let ch of shellQuoteOptions.escape.charsToEscape) {
						buffer.push(`\\${ch}`);
					}
					let regexp: RegExp = new RegExp('[' + buffer.join(',') + ']', 'g');
					let escapeChar = shellQuoteOptions.escape.escapeChar;
					return [value.replace(regexp, (match) => escapeChar + match), true];
				}
			}
			return [value, false];
		}

		function quoteIfNecessary(value: CommandString): [string, boolean] {
			if (Types.isString(value)) {
				if (needsQuotes(value)) {
					return quote(value, ShellQuoting.Strong);
				} else {
					return [value, false];
				}
			} else {
				return quote(value.value, value.quoting);
			}
		}

1085 1086 1087 1088 1089 1090 1091
		// If we have no args and the command is a string then use the command to stay backwards compatible with the old command line
		// model. To allow variable resolving with spaces we do continue if the resolved value is different than the original one
		// and the resolved one needs quoting.
		if ((!args || args.length === 0) && Types.isString(command) && (command === originalCommand as string || needsQuotes(originalCommand as string))) {
			return command;
		}

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
		let result: string[] = [];
		let commandQuoted = false;
		let argQuoted = false;
		let value: string;
		let quoted: boolean;
		[value, quoted] = quoteIfNecessary(command);
		result.push(value);
		commandQuoted = quoted;
		for (let arg of args) {
			[value, quoted] = quoteIfNecessary(arg);
			result.push(value);
			argQuoted = argQuoted || quoted;
		}

		let commandLine = result.join(' ');
		// There are special rules quoted command line in cmd.exe
1108
		if (platform === Platform.Platform.Windows) {
1109 1110 1111 1112 1113 1114 1115
			if (basename === 'cmd' && commandQuoted && argQuoted) {
				commandLine = '"' + commandLine + '"';
			} else if (basename === 'powershell' && commandQuoted) {
				commandLine = '& ' + commandLine;
			}
		}

1116
		if (basename === 'cmd' && platform === Platform.Platform.Windows && commandQuoted && argQuoted) {
1117 1118 1119
			commandLine = '"' + commandLine + '"';
		}
		return commandLine;
1120 1121
	}

A
Alex Ross 已提交
1122
	private getQuotingOptions(shellBasename: string, shellOptions: ShellConfiguration | undefined, platform: Platform.Platform): ShellQuotingOptions {
1123 1124 1125
		if (shellOptions && shellOptions.quoting) {
			return shellOptions.quoting;
		}
A
Alex Ross 已提交
1126
		return TerminalTaskSystem.shellQuotes[shellBasename] || TerminalTaskSystem.osShellQuotes[platform];
1127 1128
	}

1129
	private collectTaskVariables(variables: Set<string>, task: CustomTask | ContributedTask): void {
A
Alex Ross 已提交
1130
		if (task.command && task.command.name) {
1131
			this.collectCommandVariables(variables, task.command, task);
1132
		}
A
Alex Ross 已提交
1133
		this.collectMatcherVariables(variables, task.configurationProperties.problemMatchers);
1134 1135
	}

1136
	private collectCommandVariables(variables: Set<string>, command: CommandConfiguration, task: CustomTask | ContributedTask): void {
1137
		// The custom execution should have everything it needs already as it provided
1138
		// the callback.
G
Gabriel DeBacker 已提交
1139
		if (command.runtime === RuntimeType.CustomExecution) {
1140 1141 1142
			return;
		}

R
Rob Lourens 已提交
1143
		if (command.name === undefined) {
1144 1145
			throw new Error('Command name should never be undefined here.');
		}
1146 1147 1148 1149
		this.collectVariables(variables, command.name);
		if (command.args) {
			command.args.forEach(arg => this.collectVariables(variables, arg));
		}
1150 1151 1152 1153 1154
		// Try to get a scope.
		const scope = (<ExtensionTaskSource>task._source).scope;
		if (scope !== TaskScope.Global) {
			variables.add('${workspaceFolder}');
		}
1155 1156 1157 1158 1159
		if (command.options) {
			let options = command.options;
			if (options.cwd) {
				this.collectVariables(variables, options.cwd);
			}
1160 1161 1162 1163
			const optionsEnv = options.env;
			if (optionsEnv) {
				Object.keys(optionsEnv).forEach((key) => {
					let value: any = optionsEnv[key];
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
					if (Types.isString(value)) {
						this.collectVariables(variables, value);
					}
				});
			}
			if (options.shell) {
				if (options.shell.executable) {
					this.collectVariables(variables, options.shell.executable);
				}
				if (options.shell.args) {
					options.shell.args.forEach(arg => this.collectVariables(variables, arg));
				}
			}
		}
	}

1180
	private collectMatcherVariables(variables: Set<string>, values: Array<string | ProblemMatcher> | undefined): void {
R
Rob Lourens 已提交
1181
		if (values === undefined || values === null || values.length === 0) {
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
			return;
		}
		values.forEach((value) => {
			let matcher: ProblemMatcher;
			if (Types.isString(value)) {
				if (value[0] === '$') {
					matcher = ProblemMatcherRegistry.get(value.substring(1));
				} else {
					matcher = ProblemMatcherRegistry.get(value);
				}
			} else {
				matcher = value;
			}
			if (matcher && matcher.filePrefix) {
				this.collectVariables(variables, matcher.filePrefix);
			}
		});
	}

	private collectVariables(variables: Set<string>, value: string | CommandString): void {
		let string: string = Types.isString(value) ? value : value.value;
		let r = /\$\{(.*?)\}/g;
M
Matt Bierner 已提交
1204
		let matches: RegExpExecArray | null;
1205 1206 1207 1208 1209 1210 1211 1212 1213
		do {
			matches = r.exec(string);
			if (matches) {
				variables.add(matches[0]);
			}
		} while (matches);
	}

	private resolveCommandAndArgs(resolver: VariableResolver, commandConfig: CommandConfiguration): { command: CommandString, args: CommandString[] } {
1214
		// First we need to use the command args:
1215 1216 1217
		let args: CommandString[] = commandConfig.args ? commandConfig.args.slice() : [];
		args = this.resolveVariables(resolver, args);
		let command: CommandString = this.resolveVariable(resolver, commandConfig.name);
1218 1219 1220
		return { command, args };
	}

1221 1222 1223 1224
	private resolveVariables(resolver: VariableResolver, value: string[]): string[];
	private resolveVariables(resolver: VariableResolver, value: CommandString[]): CommandString[];
	private resolveVariables(resolver: VariableResolver, value: CommandString[]): CommandString[] {
		return value.map(s => this.resolveVariable(resolver, s));
1225 1226
	}

1227
	private resolveMatchers(resolver: VariableResolver, values: Array<string | ProblemMatcher> | undefined): ProblemMatcher[] {
R
Rob Lourens 已提交
1228
		if (values === undefined || values === null || values.length === 0) {
1229 1230
			return [];
		}
1231 1232 1233 1234
		let result: ProblemMatcher[] = [];
		values.forEach((value) => {
			let matcher: ProblemMatcher;
			if (Types.isString(value)) {
1235 1236 1237 1238 1239
				if (value[0] === '$') {
					matcher = ProblemMatcherRegistry.get(value.substring(1));
				} else {
					matcher = ProblemMatcherRegistry.get(value);
				}
1240 1241 1242 1243
			} else {
				matcher = value;
			}
			if (!matcher) {
A
Alex Ross 已提交
1244
				this.appendOutput(nls.localize('unknownProblemMatcher', 'Problem matcher {0} can\'t be resolved. The matcher will be ignored'));
1245 1246
				return;
			}
1247
			let taskSystemInfo: TaskSystemInfo | undefined = resolver.taskSystemInfo;
R
Rob Lourens 已提交
1248 1249
			let hasFilePrefix = matcher.filePrefix !== undefined;
			let hasUriProvider = taskSystemInfo !== undefined && taskSystemInfo.uriProvider !== undefined;
1250
			if (!hasFilePrefix && !hasUriProvider) {
1251 1252
				result.push(matcher);
			} else {
J
Johannes Rieken 已提交
1253
				let copy = Objects.deepClone(matcher);
R
Rob Lourens 已提交
1254
				if (hasUriProvider && (taskSystemInfo !== undefined)) {
1255
					copy.uriProvider = taskSystemInfo.uriProvider;
1256 1257
				}
				if (hasFilePrefix) {
1258
					copy.filePrefix = this.resolveVariable(resolver, copy.filePrefix);
1259
				}
1260 1261 1262 1263 1264 1265
				result.push(copy);
			}
		});
		return result;
	}

1266 1267 1268
	private resolveVariable(resolver: VariableResolver, value: string | undefined): string;
	private resolveVariable(resolver: VariableResolver, value: CommandString | undefined): CommandString;
	private resolveVariable(resolver: VariableResolver, value: CommandString | undefined): CommandString {
1269
		// TODO@Dirk Task.getWorkspaceFolder should return a WorkspaceFolder that is defined in workspace.ts
1270
		if (Types.isString(value)) {
1271
			return resolver.resolve(value);
R
Rob Lourens 已提交
1272
		} else if (value !== undefined) {
1273
			return {
1274
				value: resolver.resolve(value.value),
1275 1276
				quoting: value.quoting
			};
1277 1278
		} else { // This should never happen
			throw new Error('Should never try to resolve undefined.');
1279
		}
1280 1281
	}

1282
	private resolveOptions(resolver: VariableResolver, options: CommandOptions | undefined): CommandOptions {
R
Rob Lourens 已提交
1283
		if (options === undefined || options === null) {
1284
			return { cwd: this.resolveVariable(resolver, '${workspaceFolder}') };
1285 1286
		}
		let result: CommandOptions = Types.isString(options.cwd)
1287 1288
			? { cwd: this.resolveVariable(resolver, options.cwd) }
			: { cwd: this.resolveVariable(resolver, '${workspaceFolder}') };
1289 1290 1291
		if (options.env) {
			result.env = Object.create(null);
			Object.keys(options.env).forEach((key) => {
1292
				let value: any = options.env![key];
1293
				if (Types.isString(value)) {
1294
					result.env![key] = this.resolveVariable(resolver, value);
1295
				} else {
1296
					result.env![key] = value.toString();
1297 1298 1299 1300
				}
			});
		}
		return result;
1301 1302
	}

D
Dirk Baeumer 已提交
1303
	private registerLinkMatchers(terminal: ITerminalInstance, problemMatchers: ProblemMatcher[]): number[] {
1304
		let result: number[] = [];
D
Dirk Baeumer 已提交
1305
		/*
1306 1307 1308 1309 1310 1311 1312 1313 1314
		let handlePattern = (matcher: ProblemMatcher, pattern: ProblemPattern): void => {
			if (pattern.regexp instanceof RegExp && Types.isNumber(pattern.file)) {
				result.push(terminal.registerLinkMatcher(pattern.regexp, (match: string) => {
					let resource: URI = getResource(match, matcher);
					if (resource) {
						this.workbenchEditorService.openEditor({
							resource: resource
						});
					}
D
Dirk Baeumer 已提交
1315
				}, 0));
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
			}
		};

		for (let problemMatcher of problemMatchers) {
			if (Array.isArray(problemMatcher.pattern)) {
				for (let pattern of problemMatcher.pattern) {
					handlePattern(problemMatcher, pattern);
				}
			} else if (problemMatcher.pattern) {
				handlePattern(problemMatcher, problemMatcher.pattern);
			}
		}
D
Dirk Baeumer 已提交
1328
		*/
1329
		return result;
1330 1331
	}

1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
	private static WellKnowCommands: IStringDictionary<boolean> = {
		'ant': true,
		'cmake': true,
		'eslint': true,
		'gradle': true,
		'grunt': true,
		'gulp': true,
		'jake': true,
		'jenkins': true,
		'jshint': true,
		'make': true,
		'maven': true,
		'msbuild': true,
		'msc': true,
		'nmake': true,
		'npm': true,
		'rake': true,
		'tsc': true,
		'xbuild': true
	};
1352

1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
	public getSanitizedCommand(cmd: string): string {
		let result = cmd.toLowerCase();
		let index = result.lastIndexOf(path.sep);
		if (index !== -1) {
			result = result.substring(index + 1);
		}
		if (TerminalTaskSystem.WellKnowCommands[result]) {
			return result;
		}
		return 'other';
	}
1364 1365 1366 1367 1368 1369 1370

	private appendOutput(output: string): void {
		const outputChannel = this.outputService.getChannel(this.outputChannelId);
		if (outputChannel) {
			outputChannel.append(output);
		}
	}
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417

	private async findExecutable(command: string, cwd?: string, paths?: string[]): Promise<string> {
		// If we have an absolute path then we take it.
		if (path.isAbsolute(command)) {
			return command;
		}
		if (cwd === undefined) {
			cwd = process.cwd();
		}
		const dir = path.dirname(command);
		if (dir !== '.') {
			// We have a directory and the directory is relative (see above). Make the path absolute
			// to the current working directory.
			return path.join(cwd, command);
		}
		if (paths === undefined && Types.isString(process.env.PATH)) {
			paths = process.env.PATH.split(path.delimiter);
		}
		// No PATH environment. Make path absolute to the cwd.
		if (paths === undefined || paths.length === 0) {
			return path.join(cwd, command);
		}
		// We have a simple file name. We get the path variable from the env
		// and try to find the executable on the path.
		for (let pathEntry of paths) {
			// The path entry is absolute.
			let fullPath: string;
			if (path.isAbsolute(pathEntry)) {
				fullPath = path.join(pathEntry, command);
			} else {
				fullPath = path.join(cwd, pathEntry, command);
			}

			if (await this.fileService.exists(resources.toLocalResource(URI.from({ scheme: Schemas.file, path: fullPath }), this.environmentService.configuration.remoteAuthority))) {
				return fullPath;
			}
			let withExtension = fullPath + '.com';
			if (await this.fileService.exists(resources.toLocalResource(URI.from({ scheme: Schemas.file, path: withExtension }), this.environmentService.configuration.remoteAuthority))) {
				return withExtension;
			}
			withExtension = fullPath + '.exe';
			if (await this.fileService.exists(resources.toLocalResource(URI.from({ scheme: Schemas.file, path: withExtension }), this.environmentService.configuration.remoteAuthority))) {
				return withExtension;
			}
		}
		return path.join(cwd, command);
	}
J
Johannes Rieken 已提交
1418
}