terminalTaskSystem.ts 55.2 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
			strong: '\'',
			weak: '"'
		}
	};

	private static osShellQuotes: IStringDictionary<ShellQuotingOptions> = {
A
Alex Ross 已提交
148 149 150
		'Linux': TerminalTaskSystem.shellQuotes['bash'],
		'Mac': TerminalTaskSystem.shellQuotes['bash'],
		'Windows': TerminalTaskSystem.shellQuotes['powershell']
151 152
	};

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
			const isCustomExecution = (task.command.runtime === RuntimeType.CustomExecution) || (task.command.runtime === RuntimeType.CustomExecution2);
A
Alex Ross 已提交
475
			if (resolvedVariables && task.command && task.command.runtime && (isCustomExecution || task.command.name)) {
476
				this.currentTask.resolvedVariables = resolvedVariables;
477
				return this.executeInTerminal(task, trigger, new VariableResolver(this.currentTask.workspaceFolder!, this.currentTask.systemInfo, resolvedVariables.variables, this.configurationResolverService));
478 479 480
			} else {
				return Promise.resolve({ exitCode: 0 });
			}
A
Alex Ross 已提交
481 482
		}, reason => {
			return Promise.reject(reason);
483 484 485
		});
	}

486
	private reexecuteCommand(task: CustomTask | ContributedTask, trigger: string): Promise<ITaskSummary> {
A
Alex Ross 已提交
487 488 489 490 491 492 493
		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 => {
494
			if (value.substring(2, value.length - 1) in this.lastTask.getVerifiedTask().resolvedVariables) {
A
Alex Ross 已提交
495 496 497 498 499 500 501 502
				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 已提交
503 504
			}, reason => {
				return Promise.reject(reason);
A
Alex Ross 已提交
505 506 507 508 509 510 511
			});
		} 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 已提交
512
	private async executeInTerminal(task: CustomTask | ContributedTask, trigger: string, resolver: VariableResolver): Promise<ITaskSummary> {
513 514 515
		let terminal: ITerminalInstance | undefined = undefined;
		let executedCommand: string | undefined = undefined;
		let error: TaskError | undefined = undefined;
516
		let promise: Promise<ITaskSummary> | undefined = undefined;
A
Alex Ross 已提交
517
		if (task.configurationProperties.isBackground) {
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
			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);
539 540
							}
						}
541
					}
542
				}
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
			}));
			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!));
560
					}
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
					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 已提交
576
				});
577 578 579
			});
			promise = new Promise<ITaskSummary>((resolve, reject) => {
				const onExit = terminal!.onExit((exitCode) => {
D
Dirk Baeumer 已提交
580 581
					onData.dispose();
					onExit.dispose();
A
Alex Ross 已提交
582
					let key = task.getMapKey();
583
					delete this.activeTasks[key];
584
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Changed));
585 586 587 588 589 590 591 592 593 594
					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 已提交
595
					}
596 597 598 599
					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!);
600 601
						this.terminalService.showPanel(false);
					}
D
Dirk Baeumer 已提交
602
					watchingProblemMatcher.done();
D
Dirk Baeumer 已提交
603
					watchingProblemMatcher.dispose();
604
					registeredLinkMatchers.forEach(handle => terminal!.deregisterLinkMatcher(handle));
605
					if (!processStartedSignaled) {
606
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
607
						processStartedSignaled = true;
608
					}
G
Gabriel DeBacker 已提交
609 610 611 612 613

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

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

628 629 630 631 632 633 634 635 636 637 638 639
			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!));
640
					}
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
					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 已提交
656 657
					onData.dispose();
					onExit.dispose();
A
Alex Ross 已提交
658
					let key = task.getMapKey();
659
					delete this.activeTasks[key];
660
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Changed));
661 662 663 664 665 666 667 668 669 670
					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 已提交
671
					}
672
					let reveal = task.command.presentation!.reveal;
673 674
					let revealProblems = task.command.presentation!.revealProblems;
					let revealProblemPanel = terminal && (revealProblems === RevealProblemKind.OnProblem) && (startStopProblemMatcher.numberOfMatches > 0);
675 676 677
					if (revealProblemPanel) {
						this.panelService.openPanel(Constants.MARKERS_PANEL_ID);
					} else if (terminal && (reveal === RevealKind.Silent) && ((exitCode !== 0) || (startStopProblemMatcher.numberOfMatches > 0) && startStopProblemMatcher.maxMarkerSeverity &&
678
						(startStopProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error))) {
679 680 681
						this.terminalService.setActiveInstance(terminal);
						this.terminalService.showPanel(false);
					}
D
Dirk Baeumer 已提交
682 683
					startStopProblemMatcher.done();
					startStopProblemMatcher.dispose();
684 685 686 687 688 689 690
					registeredLinkMatchers.forEach(handle => {
						if (terminal) {
							terminal.deregisterLinkMatcher(handle);
						}
					});
					if (!processStartedSignaled && terminal) {
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal.processId!));
691
						processStartedSignaled = true;
692
					}
G
Gabriel DeBacker 已提交
693 694 695
					if (task.command.runtime !== RuntimeType.CustomExecution) {
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, exitCode));
					}
696
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Inactive, task));
697
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
D
Dirk Baeumer 已提交
698 699 700 701
					resolve({ exitCode });
				});
			});
		}
702

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

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

			// 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 已提交
854
			shellLaunchConfig = {
855
				name: terminalName,
856
				executable: executable,
857
				args: args.map(a => Types.isString(a) ? a : a.value),
858 859
				waitOnExit
			};
860 861
			if (task.command.presentation && task.command.presentation.echo) {
				let getArgsToEcho = (args: string | string[] | undefined): string => {
D
Dirk Baeumer 已提交
862 863 864 865 866 867 868 869
					if (!args || args.length === 0) {
						return '';
					}
					if (Types.isString(args)) {
						return args;
					}
					return args.join(' ');
				};
870
				if (needsFolderQualification) {
871
					shellLaunchConfig.initialText = `\x1b[1m> Executing task in folder ${this.currentTask.workspaceFolder!.name}: ${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)} <\x1b[0m\n`;
872 873 874
				} else {
					shellLaunchConfig.initialText = `\x1b[1m> Executing task: ${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)} <\x1b[0m\n`;
				}
D
Dirk Baeumer 已提交
875
			}
876
		}
A
Alex Ross 已提交
877

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

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

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

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

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

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

A
Alex Ross 已提交
939
			this.currentTask.shellLaunchConfig = this.isRerun ? this.lastTask.getVerifiedTask().shellLaunchConfig : await this.createShellLaunchConfig(task, resolver, platform, options, command, args, waitOnExit);
940 941 942
			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 已提交
943
		}
944

945 946
		let prefersSameTerminal = presentationOptions.panel === PanelKind.Dedicated;
		let allowsSharedTerminal = presentationOptions.panel === PanelKind.Shared;
947
		let group = presentationOptions.group;
948

A
Alex Ross 已提交
949
		let taskKey = task.getMapKey();
950
		let terminalToReuse: TerminalData | undefined;
951
		if (prefersSameTerminal) {
952
			let terminalId = this.sameTaskTerminals[taskKey];
953 954
			if (terminalId) {
				terminalToReuse = this.terminals[terminalId];
955
				delete this.sameTaskTerminals[taskKey];
D
Dirk Baeumer 已提交
956
			}
957
		} else if (allowsSharedTerminal) {
958 959 960 961 962 963 964 965
			// 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)!;
966
					if (idleTerminalId && this.terminals[idleTerminalId] && this.terminals[idleTerminalId].group === group) {
967 968 969 970 971
						terminalId = this.idleTaskTerminals.remove(taskId);
						break;
					}
				}
			}
972 973
			if (terminalId) {
				terminalToReuse = this.terminals[terminalId];
974
			}
D
Dirk Baeumer 已提交
975
		}
976
		if (terminalToReuse) {
977 978
			if (!this.currentTask.shellLaunchConfig) {
				throw new Error('Task shell launch configuration should not be undefined here.');
979 980
			}

981 982
			terminalToReuse.terminal.reuseTerminal(this.currentTask.shellLaunchConfig);

983
			if (task.command.presentation && task.command.presentation.clear) {
984 985
				terminalToReuse.terminal.clear();
			}
986
			this.terminals[terminalToReuse.terminal.id.toString()].lastTask = taskKey;
987
			return [terminalToReuse.terminal, commandExecutable, undefined];
988 989
		}

990 991 992 993 994 995 996
		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;
997
					await originalInstance.waitForTitle();
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
					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);
		}

1011
		const terminalKey = result.id.toString();
D
Dirk Baeumer 已提交
1012
		result.onDisposed((terminal) => {
1013
			let terminalData = this.terminals[terminalKey];
D
Dirk Baeumer 已提交
1014
			if (terminalData) {
1015
				delete this.terminals[terminalKey];
1016 1017
				delete this.sameTaskTerminals[terminalData.lastTask];
				this.idleTaskTerminals.delete(terminalData.lastTask);
1018 1019 1020 1021
				// 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 已提交
1022
				delete this.activeTasks[task.getMapKey()];
D
Dirk Baeumer 已提交
1023 1024
			}
		});
1025
		this.terminals[terminalKey] = { terminal: result, lastTask: taskKey, group };
1026
		return [result, commandExecutable, undefined];
1027 1028
	}

1029
	private buildShellCommandLine(platform: Platform.Platform, shellExecutable: string, shellOptions: ShellConfiguration | undefined, command: CommandString, originalCommand: CommandString | undefined, args: CommandString[]): string {
1030
		let basename = path.parse(shellExecutable).name.toLowerCase();
A
Alex Ross 已提交
1031
		let shellQuoteOptions = this.getQuotingOptions(basename, shellOptions, platform);
1032 1033 1034 1035 1036 1037 1038 1039

		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;
				}
			}
1040
			let quote: string | undefined;
1041
			for (let i = 0; i < value.length; i++) {
1042 1043 1044 1045
				// We found the end quote.
				let ch = value[i];
				if (ch === quote) {
					quote = undefined;
R
Rob Lourens 已提交
1046
				} else if (quote !== undefined) {
1047 1048 1049 1050 1051 1052 1053 1054
					// 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 === ' ') {
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 1085 1086 1087 1088 1089 1090 1091 1092 1093
					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);
			}
		}

1094 1095 1096 1097 1098 1099 1100
		// 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;
		}

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
		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
1117
		if (platform === Platform.Platform.Windows) {
1118 1119 1120 1121 1122 1123 1124
			if (basename === 'cmd' && commandQuoted && argQuoted) {
				commandLine = '"' + commandLine + '"';
			} else if (basename === 'powershell' && commandQuoted) {
				commandLine = '& ' + commandLine;
			}
		}

1125
		if (basename === 'cmd' && platform === Platform.Platform.Windows && commandQuoted && argQuoted) {
1126 1127 1128
			commandLine = '"' + commandLine + '"';
		}
		return commandLine;
1129 1130
	}

A
Alex Ross 已提交
1131
	private getQuotingOptions(shellBasename: string, shellOptions: ShellConfiguration | undefined, platform: Platform.Platform): ShellQuotingOptions {
1132 1133 1134
		if (shellOptions && shellOptions.quoting) {
			return shellOptions.quoting;
		}
A
Alex Ross 已提交
1135
		return TerminalTaskSystem.shellQuotes[shellBasename] || TerminalTaskSystem.osShellQuotes[Platform.PlatformToString(platform)];
1136 1137
	}

1138
	private collectTaskVariables(variables: Set<string>, task: CustomTask | ContributedTask): void {
A
Alex Ross 已提交
1139
		if (task.command && task.command.name) {
1140
			this.collectCommandVariables(variables, task.command, task);
1141
		}
A
Alex Ross 已提交
1142
		this.collectMatcherVariables(variables, task.configurationProperties.problemMatchers);
1143 1144
	}

1145
	private collectCommandVariables(variables: Set<string>, command: CommandConfiguration, task: CustomTask | ContributedTask): void {
1146
		// The custom execution should have everything it needs already as it provided
1147
		// the callback.
1148
		if ((command.runtime === RuntimeType.CustomExecution) || (command.runtime === RuntimeType.CustomExecution2)) {
1149 1150 1151
			return;
		}

R
Rob Lourens 已提交
1152
		if (command.name === undefined) {
1153 1154
			throw new Error('Command name should never be undefined here.');
		}
1155 1156 1157 1158
		this.collectVariables(variables, command.name);
		if (command.args) {
			command.args.forEach(arg => this.collectVariables(variables, arg));
		}
1159 1160 1161 1162 1163
		// Try to get a scope.
		const scope = (<ExtensionTaskSource>task._source).scope;
		if (scope !== TaskScope.Global) {
			variables.add('${workspaceFolder}');
		}
1164 1165 1166 1167 1168
		if (command.options) {
			let options = command.options;
			if (options.cwd) {
				this.collectVariables(variables, options.cwd);
			}
1169 1170 1171 1172
			const optionsEnv = options.env;
			if (optionsEnv) {
				Object.keys(optionsEnv).forEach((key) => {
					let value: any = optionsEnv[key];
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
					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));
				}
			}
		}
	}

1189
	private collectMatcherVariables(variables: Set<string>, values: Array<string | ProblemMatcher> | undefined): void {
R
Rob Lourens 已提交
1190
		if (values === undefined || values === null || values.length === 0) {
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
			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 已提交
1213
		let matches: RegExpExecArray | null;
1214 1215 1216 1217 1218 1219 1220 1221 1222
		do {
			matches = r.exec(string);
			if (matches) {
				variables.add(matches[0]);
			}
		} while (matches);
	}

	private resolveCommandAndArgs(resolver: VariableResolver, commandConfig: CommandConfiguration): { command: CommandString, args: CommandString[] } {
1223
		// First we need to use the command args:
1224 1225 1226
		let args: CommandString[] = commandConfig.args ? commandConfig.args.slice() : [];
		args = this.resolveVariables(resolver, args);
		let command: CommandString = this.resolveVariable(resolver, commandConfig.name);
1227 1228 1229
		return { command, args };
	}

1230 1231 1232 1233
	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));
1234 1235
	}

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

1275 1276 1277
	private resolveVariable(resolver: VariableResolver, value: string | undefined): string;
	private resolveVariable(resolver: VariableResolver, value: CommandString | undefined): CommandString;
	private resolveVariable(resolver: VariableResolver, value: CommandString | undefined): CommandString {
1278
		// TODO@Dirk Task.getWorkspaceFolder should return a WorkspaceFolder that is defined in workspace.ts
1279
		if (Types.isString(value)) {
1280
			return resolver.resolve(value);
R
Rob Lourens 已提交
1281
		} else if (value !== undefined) {
1282
			return {
1283
				value: resolver.resolve(value.value),
1284 1285
				quoting: value.quoting
			};
1286 1287
		} else { // This should never happen
			throw new Error('Should never try to resolve undefined.');
1288
		}
1289 1290
	}

1291
	private resolveOptions(resolver: VariableResolver, options: CommandOptions | undefined): CommandOptions {
R
Rob Lourens 已提交
1292
		if (options === undefined || options === null) {
1293
			return { cwd: this.resolveVariable(resolver, '${workspaceFolder}') };
1294 1295
		}
		let result: CommandOptions = Types.isString(options.cwd)
1296 1297
			? { cwd: this.resolveVariable(resolver, options.cwd) }
			: { cwd: this.resolveVariable(resolver, '${workspaceFolder}') };
1298 1299 1300
		if (options.env) {
			result.env = Object.create(null);
			Object.keys(options.env).forEach((key) => {
1301
				let value: any = options.env![key];
1302
				if (Types.isString(value)) {
1303
					result.env![key] = this.resolveVariable(resolver, value);
1304
				} else {
1305
					result.env![key] = value.toString();
1306 1307 1308 1309
				}
			});
		}
		return result;
1310 1311
	}

D
Dirk Baeumer 已提交
1312
	private registerLinkMatchers(terminal: ITerminalInstance, problemMatchers: ProblemMatcher[]): number[] {
1313
		let result: number[] = [];
D
Dirk Baeumer 已提交
1314
		/*
1315 1316 1317 1318 1319 1320 1321 1322 1323
		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 已提交
1324
				}, 0));
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
			}
		};

		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 已提交
1337
		*/
1338
		return result;
1339 1340
	}

1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
	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
	};
1361

1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
	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';
	}
1373 1374 1375 1376 1377 1378 1379

	private appendOutput(output: string): void {
		const outputChannel = this.outputService.getChannel(this.outputChannelId);
		if (outputChannel) {
			outputChannel.append(output);
		}
	}
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 1418 1419 1420 1421 1422 1423 1424 1425 1426

	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 已提交
1427
}