terminalTaskSystem.ts 54.6 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';
M
Matt Bierner 已提交
17
import { DisposableStore } 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) => {
D
Daniel Imms 已提交
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> {
464 465 466
		const workspaceFolder = this.currentTask.workspaceFolder = task.getWorkspaceFolder();
		if (workspaceFolder === undefined) {
			return Promise.reject(new Error(`Must have workspace folder${task._label}`));
A
Alex Ross 已提交
467
		}
468
		const systemInfo = this.currentTask.systemInfo = this.taskSystemInfoResolver(workspaceFolder);
A
Alex Ross 已提交
469 470 471

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

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

487
	private reexecuteCommand(task: CustomTask | ContributedTask, trigger: string): Promise<ITaskSummary> {
488
		const workspaceFolder = this.currentTask.workspaceFolder = this.lastTask.workspaceFolder;
A
Alex Ross 已提交
489 490 491 492 493 494
		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 => {
495
			if (value.substring(2, value.length - 1) in this.lastTask.getVerifiedTask().resolvedVariables) {
A
Alex Ross 已提交
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;
503
				return this.executeInTerminal(task, trigger, new VariableResolver(this.lastTask.getVerifiedTask().workspaceFolder, this.lastTask.getVerifiedTask().systemInfo, resolvedVariables.variables, this.configurationResolverService), workspaceFolder!);
A
Alex Ross 已提交
504 505
			}, reason => {
				return Promise.reject(reason);
A
Alex Ross 已提交
506 507 508
			});
		} else {
			this.currentTask.resolvedVariables = this.lastTask.getVerifiedTask().resolvedVariables;
509
			return this.executeInTerminal(task, trigger, new VariableResolver(this.lastTask.getVerifiedTask().workspaceFolder, this.lastTask.getVerifiedTask().systemInfo, this.lastTask.getVerifiedTask().resolvedVariables.variables, this.configurationResolverService), workspaceFolder!);
A
Alex Ross 已提交
510 511 512
		}
	}

513
	private async executeInTerminal(task: CustomTask | ContributedTask, trigger: string, resolver: VariableResolver, workspaceFolder: IWorkspaceFolder): Promise<ITaskSummary> {
514 515 516
		let terminal: ITerminalInstance | undefined = undefined;
		let executedCommand: string | undefined = undefined;
		let error: TaskError | undefined = undefined;
517
		let promise: Promise<ITaskSummary> | undefined = undefined;
A
Alex Ross 已提交
518
		if (task.configurationProperties.isBackground) {
519 520
			const problemMatchers = this.resolveMatchers(resolver, task.configurationProperties.problemMatchers);
			let watchingProblemMatcher = new WatchingProblemCollector(problemMatchers, this.markerService, this.modelService, this.fileService);
M
Matt Bierner 已提交
521
			const toDispose = new DisposableStore();
522
			let eventCounter: number = 0;
M
Matt Bierner 已提交
523
			toDispose.add(watchingProblemMatcher.onDidStateChange((event) => {
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
				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);
540 541
							}
						}
542
					}
543
				}
544 545 546
			}));
			watchingProblemMatcher.aboutToStart();
			let delayer: Async.Delayer<any> | undefined = undefined;
547
			[terminal, executedCommand, error] = await this.createTerminal(task, resolver, workspaceFolder);
548 549 550 551 552 553 554 555 556 557 558

			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) {
A
Alex Ross 已提交
559
					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
					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

A
Alex Ross 已提交
609
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, exitCode));
G
Gabriel DeBacker 已提交
610

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

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

					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, exitCode));
689
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Inactive, task));
690
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
D
Dirk Baeumer 已提交
691 692 693 694
					resolve({ exitCode });
				});
			});
		}
695

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

749 750
	private createTerminalName(task: CustomTask | ContributedTask, workspaceFolder: IWorkspaceFolder): string {
		const needsFolderQualification = this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE;
751 752 753
		return nls.localize('TerminalTaskSystem.terminalName', 'Task - {0}', needsFolderQualification ? task.getQualifiedLabel() : task.configurationProperties.name);
	}

A
Alex Ross 已提交
754 755 756 757 758 759 760 761
	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 });
	}

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

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

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

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

A
Alex Ross 已提交
892
		let waitOnExit: boolean | string = false;
893 894 895 896
		const presentationOptions = task.command.presentation;
		if (!presentationOptions) {
			throw new Error('Task presentation options should not be undefined here.');
		}
A
Alex Ross 已提交
897

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

		let commandExecutable: string | undefined;
		let command: CommandString | undefined;
		let args: CommandString[] | undefined;
911
		let launchConfigs: IShellLaunchConfig | undefined;
912

A
Alex Ross 已提交
913
		if (task.command.runtime === RuntimeType.CustomExecution2) {
914
			this.currentTask.shellLaunchConfig = launchConfigs = {
915
				isExtensionTerminal: true,
916
				waitOnExit,
917
				name: this.createTerminalName(task, workspaceFolder),
918 919
				initialText: task.command.presentation && task.command.presentation.echo ? `\x1b[1m> Executing task: ${task._label} <\x1b[0m\n` : undefined
			};
920
		} else {
921 922 923 924 925
			let resolvedResult: { command: CommandString, args: CommandString[] } = this.resolveCommandAndArgs(resolver, task.command);
			command = resolvedResult.command;
			args = resolvedResult.args;
			commandExecutable = CommandString.value(command);

926 927
			this.currentTask.shellLaunchConfig = launchConfigs = this.isRerun ? this.lastTask.getVerifiedTask().shellLaunchConfig : await this.createShellLaunchConfig(task, workspaceFolder, resolver, platform, options, command, args, waitOnExit);
			if (launchConfigs === undefined) {
928 929
				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 已提交
930
		}
931

932 933
		let prefersSameTerminal = presentationOptions.panel === PanelKind.Dedicated;
		let allowsSharedTerminal = presentationOptions.panel === PanelKind.Shared;
934
		let group = presentationOptions.group;
935

A
Alex Ross 已提交
936
		let taskKey = task.getMapKey();
937
		let terminalToReuse: TerminalData | undefined;
938
		if (prefersSameTerminal) {
939
			let terminalId = this.sameTaskTerminals[taskKey];
940 941
			if (terminalId) {
				terminalToReuse = this.terminals[terminalId];
942
				delete this.sameTaskTerminals[taskKey];
D
Dirk Baeumer 已提交
943
			}
944
		} else if (allowsSharedTerminal) {
945 946 947 948 949 950 951 952
			// 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)!;
953
					if (idleTerminalId && this.terminals[idleTerminalId] && this.terminals[idleTerminalId].group === group) {
954 955 956 957 958
						terminalId = this.idleTaskTerminals.remove(taskId);
						break;
					}
				}
			}
959 960
			if (terminalId) {
				terminalToReuse = this.terminals[terminalId];
961
			}
D
Dirk Baeumer 已提交
962
		}
963
		if (terminalToReuse) {
964
			if (!launchConfigs) {
965
				throw new Error('Task shell launch configuration should not be undefined here.');
966 967
			}

968
			terminalToReuse.terminal.reuseTerminal(launchConfigs);
969

970
			if (task.command.presentation && task.command.presentation.clear) {
971 972
				terminalToReuse.terminal.clear();
			}
973
			this.terminals[terminalToReuse.terminal.id.toString()].lastTask = taskKey;
974
			return [terminalToReuse.terminal, commandExecutable, undefined];
975 976
		}

977 978 979 980 981 982 983
		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;
984
					await originalInstance.waitForTitle();
985
					result = this.terminalService.splitInstance(originalInstance, launchConfigs);
986 987 988 989 990 991 992 993
					if (result) {
						break;
					}
				}
			}
		}
		if (!result) {
			// Either no group is used, no terminal with the group exists or splitting an existing terminal failed.
994
			result = this.terminalService.createTerminal(launchConfigs);
995 996
		}

997
		const terminalKey = result.id.toString();
D
Dirk Baeumer 已提交
998
		result.onDisposed((terminal) => {
999
			let terminalData = this.terminals[terminalKey];
D
Dirk Baeumer 已提交
1000
			if (terminalData) {
1001
				delete this.terminals[terminalKey];
1002 1003
				delete this.sameTaskTerminals[terminalData.lastTask];
				this.idleTaskTerminals.delete(terminalData.lastTask);
1004 1005 1006 1007
				// 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 已提交
1008
				delete this.activeTasks[task.getMapKey()];
D
Dirk Baeumer 已提交
1009 1010
			}
		});
1011
		this.terminals[terminalKey] = { terminal: result, lastTask: taskKey, group };
1012
		return [result, commandExecutable, undefined];
1013 1014
	}

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

		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;
				}
			}
1026
			let quote: string | undefined;
1027
			for (let i = 0; i < value.length; i++) {
1028 1029 1030 1031
				// We found the end quote.
				let ch = value[i];
				if (ch === quote) {
					quote = undefined;
R
Rob Lourens 已提交
1032
				} else if (quote !== undefined) {
1033 1034 1035 1036 1037 1038 1039 1040
					// 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 === ' ') {
1041 1042 1043 1044 1045 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
					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);
			}
		}

1080 1081 1082 1083 1084 1085 1086
		// 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;
		}

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
		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
1103
		if (platform === Platform.Platform.Windows) {
1104 1105 1106 1107 1108 1109 1110
			if (basename === 'cmd' && commandQuoted && argQuoted) {
				commandLine = '"' + commandLine + '"';
			} else if (basename === 'powershell' && commandQuoted) {
				commandLine = '& ' + commandLine;
			}
		}

1111
		if (basename === 'cmd' && platform === Platform.Platform.Windows && commandQuoted && argQuoted) {
1112 1113 1114
			commandLine = '"' + commandLine + '"';
		}
		return commandLine;
1115 1116
	}

A
Alex Ross 已提交
1117
	private getQuotingOptions(shellBasename: string, shellOptions: ShellConfiguration | undefined, platform: Platform.Platform): ShellQuotingOptions {
1118 1119 1120
		if (shellOptions && shellOptions.quoting) {
			return shellOptions.quoting;
		}
A
Alex Ross 已提交
1121
		return TerminalTaskSystem.shellQuotes[shellBasename] || TerminalTaskSystem.osShellQuotes[Platform.PlatformToString(platform)];
1122 1123
	}

1124
	private collectTaskVariables(variables: Set<string>, task: CustomTask | ContributedTask): void {
A
Alex Ross 已提交
1125
		if (task.command && task.command.name) {
1126
			this.collectCommandVariables(variables, task.command, task);
1127
		}
A
Alex Ross 已提交
1128
		this.collectMatcherVariables(variables, task.configurationProperties.problemMatchers);
1129 1130
	}

1131
	private collectCommandVariables(variables: Set<string>, command: CommandConfiguration, task: CustomTask | ContributedTask): void {
1132
		// The custom execution should have everything it needs already as it provided
1133
		// the callback.
A
Alex Ross 已提交
1134
		if (command.runtime === RuntimeType.CustomExecution2) {
1135 1136 1137
			return;
		}

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

1175
	private collectMatcherVariables(variables: Set<string>, values: Array<string | ProblemMatcher> | undefined): void {
R
Rob Lourens 已提交
1176
		if (values === undefined || values === null || values.length === 0) {
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
			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 已提交
1199
		let matches: RegExpExecArray | null;
1200 1201 1202 1203 1204 1205 1206 1207 1208
		do {
			matches = r.exec(string);
			if (matches) {
				variables.add(matches[0]);
			}
		} while (matches);
	}

	private resolveCommandAndArgs(resolver: VariableResolver, commandConfig: CommandConfiguration): { command: CommandString, args: CommandString[] } {
1209
		// First we need to use the command args:
1210 1211 1212
		let args: CommandString[] = commandConfig.args ? commandConfig.args.slice() : [];
		args = this.resolveVariables(resolver, args);
		let command: CommandString = this.resolveVariable(resolver, commandConfig.name);
1213 1214 1215
		return { command, args };
	}

1216 1217 1218 1219
	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));
1220 1221
	}

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

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

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

D
Dirk Baeumer 已提交
1298
	private registerLinkMatchers(terminal: ITerminalInstance, problemMatchers: ProblemMatcher[]): number[] {
1299
		let result: number[] = [];
D
Dirk Baeumer 已提交
1300
		/*
1301 1302 1303 1304 1305 1306 1307 1308 1309
		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 已提交
1310
				}, 0));
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
			}
		};

		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 已提交
1323
		*/
1324
		return result;
1325 1326
	}

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
	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
	};
1347

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
	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';
	}
1359 1360 1361 1362 1363 1364 1365

	private appendOutput(output: string): void {
		const outputChannel = this.outputService.getChannel(this.outputChannelId);
		if (outputChannel) {
			outputChannel.append(output);
		}
	}
1366 1367 1368 1369 1370 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

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