terminalTaskSystem.ts 55.0 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;
158 159 160 161
	private lastTask: VerifiedTask | undefined;
	// Should always be set in run
	private currentTask!: VerifiedTask;
	private isRerun: boolean = false;
162

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

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

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

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

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

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

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

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

220
		try {
A
Alex Ross 已提交
221
			const executeResult = { kind: TaskExecuteKind.Started, task, started: {}, promise: this.executeTask(task, resolver, trigger) };
222 223 224
			executeResult.promise.then(summary => {
				this.lastTask = this.currentTask;
			});
A
Alex Ross 已提交
225
			return executeResult;
226 227 228 229 230 231 232 233 234 235 236 237 238
		} 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 已提交
239 240
	public rerun(): ITaskExecuteResult | undefined {
		if (this.lastTask && this.lastTask.verify()) {
R
Rob Lourens 已提交
241
			if ((this.lastTask.task.runOptions.reevaluateOnRerun !== undefined) && !this.lastTask.task.runOptions.reevaluateOnRerun) {
A
Alex Ross 已提交
242 243 244
				this.isRerun = true;
			}
			const result = this.run(this.lastTask.task, this.lastTask.resolver);
245 246 247
			result.promise.then(summary => {
				this.isRerun = false;
			});
A
Alex Ross 已提交
248 249 250 251 252
			return result;
		} else {
			return undefined;
		}
	}
253 254

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

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

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

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

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

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

		return new Promise<void>((resolve) => {
D
Daniel Imms 已提交
289
			// activeTerminal.terminal.rendererExit(result);
290 291 292 293
			resolve();
		});
	}

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

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

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

339
	private async executeTask(task: Task, resolver: ITaskResolver, trigger: string): Promise<ITaskSummary> {
340
		let promises: Promise<ITaskSummary>[] = [];
A
Alex Ross 已提交
341
		if (task.configurationProperties.dependsOn) {
B
Benjamin Pasero 已提交
342
			// tslint:disable-next-line: no-for-in-array
343 344
			for (let index in task.configurationProperties.dependsOn) {
				const dependency = task.configurationProperties.dependsOn[index];
345 346 347
				let dependencyTask = resolver.resolve(dependency.workspaceFolder, dependency.task!);
				if (dependencyTask) {
					let key = dependencyTask.getMapKey();
348
					let promise = this.activeTasks[key] ? this.activeTasks[key].promise : undefined;
D
Dirk Baeumer 已提交
349
					if (!promise) {
350 351
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.DependsOnStarted, task));
						promise = this.executeTask(dependencyTask, resolver, trigger);
D
Dirk Baeumer 已提交
352
					}
353 354 355
					if (task.configurationProperties.dependsOrder === DependsOrder.sequence) {
						promise = Promise.resolve(await promise);
					}
D
Dirk Baeumer 已提交
356
					promises.push(promise);
357
				} else {
358 359 360 361 362
					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
					));
363
					this.showOutput();
D
Dirk Baeumer 已提交
364
				}
365
			}
D
Dirk Baeumer 已提交
366 367
		}

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

393
	private resolveVariablesFromSet(taskSystemInfo: TaskSystemInfo | undefined, workspaceFolder: IWorkspaceFolder, task: CustomTask | ContributedTask, variables: Set<string>): Promise<ResolvedVariables> {
394 395 396 397 398 399 400 401 402 403 404 405 406 407
		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 已提交
408

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

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

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

465
	private executeCommand(task: CustomTask | ContributedTask, trigger: string): Promise<ITaskSummary> {
466 467 468
		const workspaceFolder = this.currentTask.workspaceFolder = task.getWorkspaceFolder();
		if (workspaceFolder === undefined) {
			return Promise.reject(new Error(`Must have workspace folder${task._label}`));
A
Alex Ross 已提交
469
		}
470
		const systemInfo = this.currentTask.systemInfo = this.taskSystemInfoResolver(workspaceFolder);
A
Alex Ross 已提交
471 472 473

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

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

489
	private reexecuteCommand(task: CustomTask | ContributedTask, trigger: string): Promise<ITaskSummary> {
490 491 492 493 494
		const lastTask = this.lastTask;
		if (!lastTask) {
			return Promise.reject(new Error('No task previously run'));
		}
		const workspaceFolder = this.currentTask.workspaceFolder = lastTask.workspaceFolder;
A
Alex Ross 已提交
495 496 497 498 499 500
		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 => {
501
			if (value.substring(2, value.length - 1) in lastTask.getVerifiedTask().resolvedVariables) {
A
Alex Ross 已提交
502 503 504 505 506
				hasAllVariables = false;
			}
		});

		if (!hasAllVariables) {
507
			return this.resolveVariablesFromSet(lastTask.getVerifiedTask().systemInfo, lastTask.getVerifiedTask().workspaceFolder, task, variables).then((resolvedVariables) => {
A
Alex Ross 已提交
508
				this.currentTask.resolvedVariables = resolvedVariables;
509
				return this.executeInTerminal(task, trigger, new VariableResolver(lastTask.getVerifiedTask().workspaceFolder, lastTask.getVerifiedTask().systemInfo, resolvedVariables.variables, this.configurationResolverService), workspaceFolder!);
A
Alex Ross 已提交
510 511
			}, reason => {
				return Promise.reject(reason);
A
Alex Ross 已提交
512 513
			});
		} else {
514 515
			this.currentTask.resolvedVariables = lastTask.getVerifiedTask().resolvedVariables;
			return this.executeInTerminal(task, trigger, new VariableResolver(lastTask.getVerifiedTask().workspaceFolder, lastTask.getVerifiedTask().systemInfo, lastTask.getVerifiedTask().resolvedVariables.variables, this.configurationResolverService), workspaceFolder!);
A
Alex Ross 已提交
516 517 518
		}
	}

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

			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 已提交
565
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
					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 已提交
581
				});
582 583 584
			});
			promise = new Promise<ITaskSummary>((resolve, reject) => {
				const onExit = terminal!.onExit((exitCode) => {
D
Dirk Baeumer 已提交
585 586
					onData.dispose();
					onExit.dispose();
A
Alex Ross 已提交
587
					let key = task.getMapKey();
588
					delete this.activeTasks[key];
589
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Changed));
590 591 592 593 594 595 596 597 598 599
					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 已提交
600
					}
601 602 603 604
					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!);
605 606
						this.terminalService.showPanel(false);
					}
D
Dirk Baeumer 已提交
607
					watchingProblemMatcher.done();
D
Dirk Baeumer 已提交
608
					watchingProblemMatcher.dispose();
609
					registeredLinkMatchers.forEach(handle => terminal!.deregisterLinkMatcher(handle));
610
					if (!processStartedSignaled) {
611
						this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
612
						processStartedSignaled = true;
613
					}
G
Gabriel DeBacker 已提交
614

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

D
Dirk Baeumer 已提交
617
					for (let i = 0; i < eventCounter; i++) {
618 619
						let event = TaskEvent.create(TaskEventKind.Inactive, task);
						this._onDidStateChange.fire(event);
D
Dirk Baeumer 已提交
620 621
					}
					eventCounter = 0;
622
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
M
Matt Bierner 已提交
623
					toDispose.dispose();
D
Dirk Baeumer 已提交
624 625 626 627
					resolve({ exitCode });
				});
			});
		} else {
628
			[terminal, executedCommand, error] = await this.createTerminal(task, resolver, workspaceFolder);
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) {
A
Alex Ross 已提交
640
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.processId!));
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
					}
A
Alex Ross 已提交
693 694

					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.ProcessEnded, task, exitCode));
695
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.Inactive, task));
696
					this._onDidStateChange.fire(TaskEvent.create(TaskEventKind.End, task));
D
Dirk Baeumer 已提交
697 698 699 700
					resolve({ exitCode });
				});
			});
		}
701

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

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

A
Alex Ross 已提交
760 761 762 763 764 765 766 767
	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 });
	}

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

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

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

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

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

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

		let commandExecutable: string | undefined;
		let command: CommandString | undefined;
		let args: CommandString[] | undefined;
917
		let launchConfigs: IShellLaunchConfig | undefined;
918

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

932
			this.currentTask.shellLaunchConfig = launchConfigs = (this.isRerun && this.lastTask) ? this.lastTask.getVerifiedTask().shellLaunchConfig : await this.createShellLaunchConfig(task, workspaceFolder, resolver, platform, options, command, args, waitOnExit);
933
			if (launchConfigs === undefined) {
934 935
				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 已提交
936
		}
937

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

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

974
			terminalToReuse.terminal.reuseTerminal(launchConfigs);
975

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

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

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

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

		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;
				}
			}
1032
			let quote: string | undefined;
1033
			for (let i = 0; i < value.length; i++) {
1034 1035 1036 1037
				// We found the end quote.
				let ch = value[i];
				if (ch === quote) {
					quote = undefined;
R
Rob Lourens 已提交
1038
				} else if (quote !== undefined) {
1039 1040 1041 1042 1043 1044 1045 1046
					// 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 === ' ') {
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
					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);
			}
		}

1086 1087 1088 1089 1090 1091 1092
		// 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;
		}

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

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

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

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

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

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

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

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

1222 1223 1224 1225
	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));
1226 1227
	}

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

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

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

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

		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 已提交
1329
		*/
1330
		return result;
1331 1332
	}

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
	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
	};
1353

1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
	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';
	}
1365 1366 1367 1368 1369 1370 1371

	private appendOutput(output: string): void {
		const outputChannel = this.outputService.getChannel(this.outputChannelId);
		if (outputChannel) {
			outputChannel.append(output);
		}
	}
1372 1373 1374 1375 1376 1377 1378

	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) {
B
Benjamin Pasero 已提交
1379
			// tslint:disable-next-line: no-nodejs-globals
1380 1381 1382 1383 1384 1385 1386 1387
			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);
		}
B
Benjamin Pasero 已提交
1388
		// tslint:disable-next-line: no-nodejs-globals
1389
		if (paths === undefined && Types.isString(process.env.PATH)) {
B
Benjamin Pasero 已提交
1390
			// tslint:disable-next-line: no-nodejs-globals
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
			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 已提交
1422
}