@theia/task 1.53.0-next.4 → 1.53.0-next.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +193 -193
  2. package/lib/browser/task-schema-updater.js +1 -1
  3. package/package.json +13 -13
  4. package/src/browser/index.ts +22 -22
  5. package/src/browser/process/process-task-contribution.ts +31 -31
  6. package/src/browser/process/process-task-frontend-module.ts +27 -27
  7. package/src/browser/process/process-task-resolver.ts +89 -89
  8. package/src/browser/provided-task-configurations.spec.ts +46 -46
  9. package/src/browser/provided-task-configurations.ts +213 -213
  10. package/src/browser/quick-open-task.ts +831 -831
  11. package/src/browser/style/index.css +19 -19
  12. package/src/browser/task-configuration-manager.ts +256 -256
  13. package/src/browser/task-configuration-model.ts +101 -101
  14. package/src/browser/task-configurations.ts +508 -508
  15. package/src/browser/task-contribution.ts +266 -266
  16. package/src/browser/task-definition-registry.spec.ts +203 -203
  17. package/src/browser/task-definition-registry.ts +131 -131
  18. package/src/browser/task-frontend-contribution.ts +402 -402
  19. package/src/browser/task-frontend-module.ts +86 -86
  20. package/src/browser/task-name-resolver.ts +55 -55
  21. package/src/browser/task-node.ts +37 -37
  22. package/src/browser/task-preferences.ts +40 -40
  23. package/src/browser/task-problem-matcher-registry.ts +308 -308
  24. package/src/browser/task-problem-pattern-registry.ts +196 -196
  25. package/src/browser/task-schema-updater.ts +701 -701
  26. package/src/browser/task-service.ts +1164 -1164
  27. package/src/browser/task-source-resolver.ts +36 -36
  28. package/src/browser/task-templates.ts +168 -168
  29. package/src/browser/task-terminal-widget-manager.ts +224 -224
  30. package/src/browser/tasks-monaco-contribution.ts +27 -27
  31. package/src/common/index.ts +20 -20
  32. package/src/common/problem-matcher-protocol.ts +234 -234
  33. package/src/common/process/task-protocol.ts +97 -97
  34. package/src/common/task-common-module.ts +34 -34
  35. package/src/common/task-protocol.ts +317 -317
  36. package/src/common/task-util.ts +43 -43
  37. package/src/common/task-watcher.ts +78 -78
  38. package/src/node/custom/custom-task-runner-backend-module.ts +37 -37
  39. package/src/node/custom/custom-task-runner-contribution.ts +30 -30
  40. package/src/node/custom/custom-task-runner.ts +60 -60
  41. package/src/node/custom/custom-task.ts +73 -73
  42. package/src/node/index.ts +19 -19
  43. package/src/node/process/process-task-runner-backend-module.ts +37 -37
  44. package/src/node/process/process-task-runner-contribution.ts +31 -31
  45. package/src/node/process/process-task-runner.ts +371 -371
  46. package/src/node/process/process-task.spec.ts +30 -30
  47. package/src/node/process/process-task.ts +144 -144
  48. package/src/node/task-abstract-line-matcher.ts +312 -312
  49. package/src/node/task-backend-application-contribution.ts +36 -36
  50. package/src/node/task-backend-module.ts +57 -57
  51. package/src/node/task-line-matchers.ts +127 -127
  52. package/src/node/task-manager.ts +129 -129
  53. package/src/node/task-problem-collector.spec.ts +338 -338
  54. package/src/node/task-problem-collector.ts +62 -62
  55. package/src/node/task-runner-protocol.ts +33 -33
  56. package/src/node/task-runner.ts +96 -96
  57. package/src/node/task-server.slow-spec.ts +444 -444
  58. package/src/node/task-server.ts +263 -263
  59. package/src/node/task.ts +103 -103
  60. package/src/node/test/task-test-container.ts +63 -63
@@ -1,371 +1,371 @@
1
- // *****************************************************************************
2
- // Copyright (C) 2017-2019 Ericsson and others.
3
- //
4
- // This program and the accompanying materials are made available under the
5
- // terms of the Eclipse Public License v. 2.0 which is available at
6
- // http://www.eclipse.org/legal/epl-2.0.
7
- //
8
- // This Source Code may also be made available under the following Secondary
9
- // Licenses when the conditions for such availability set forth in the Eclipse
10
- // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
- // with the GNU Classpath Exception which is available at
12
- // https://www.gnu.org/software/classpath/license.html.
13
- //
14
- // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
15
- // *****************************************************************************
16
-
17
- /*---------------------------------------------------------------------------------------------
18
- * Copyright (c) Microsoft Corporation. All rights reserved.
19
- * Licensed under the MIT License. See License.txt in the project root for license information.
20
- *--------------------------------------------------------------------------------------------*/
21
-
22
- import { injectable, inject, named } from '@theia/core/shared/inversify';
23
- import { deepClone, isWindows, isOSX, ILogger } from '@theia/core';
24
- import { FileUri } from '@theia/core/lib/node';
25
- import {
26
- RawProcessFactory,
27
- ProcessErrorEvent,
28
- Process,
29
- TerminalProcessOptions,
30
- TaskTerminalProcessFactory,
31
- } from '@theia/process/lib/node';
32
- import {
33
- ShellQuotedString, ShellQuotingFunctions, BashQuotingFunctions, CmdQuotingFunctions, PowershellQuotingFunctions, createShellCommandLine, ShellQuoting,
34
- } from '@theia/process/lib/common/shell-quoting';
35
- import { TaskFactory } from './process-task';
36
- import { TaskRunner } from '../task-runner-protocol';
37
- import { Task } from '../task';
38
- import { TaskConfiguration } from '../../common/task-protocol';
39
- import { ProcessTaskError, CommandOptions } from '../../common/process/task-protocol';
40
- import * as fs from 'fs';
41
- import { ShellProcess } from '@theia/terminal/lib/node/shell-process';
42
-
43
- export interface OsSpecificCommand {
44
- command: string,
45
- args: Array<string | ShellQuotedString> | undefined,
46
- options: CommandOptions
47
- }
48
-
49
- export interface ShellSpecificOptions {
50
- /** Arguments passed to the shell, aka `command` here. */
51
- execArgs: string[];
52
- /** Pack of functions used to escape the `subCommand` and `subArgs` to run in the shell. */
53
- quotingFunctions?: ShellQuotingFunctions;
54
- }
55
-
56
- /**
57
- * Task runner that runs a task as a process or a command inside a shell.
58
- */
59
- @injectable()
60
- export class ProcessTaskRunner implements TaskRunner {
61
-
62
- @inject(ILogger) @named('task')
63
- protected readonly logger: ILogger;
64
-
65
- @inject(RawProcessFactory)
66
- protected readonly rawProcessFactory: RawProcessFactory;
67
-
68
- @inject(TaskTerminalProcessFactory)
69
- protected readonly taskTerminalProcessFactory: TaskTerminalProcessFactory;
70
-
71
- @inject(TaskFactory)
72
- protected readonly taskFactory: TaskFactory;
73
-
74
- /**
75
- * Runs a task from the given task configuration.
76
- * @param taskConfig task configuration to run a task from. The provided task configuration must have a shape of `CommandProperties`.
77
- */
78
- async run(taskConfig: TaskConfiguration, ctx?: string): Promise<Task> {
79
- if (!taskConfig.command) {
80
- throw new Error("Process task config must have 'command' property specified");
81
- }
82
- try {
83
- // Always spawn a task in a pty, the only difference between shell/process tasks is the
84
- // way the command is passed:
85
- // - process: directly look for an executable and pass a specific set of arguments/options.
86
- // - shell: defer the spawning to a shell that will evaluate a command line with our executable.
87
- const terminalProcessOptions = this.getResolvedCommand(taskConfig);
88
- const terminal: Process = this.taskTerminalProcessFactory(terminalProcessOptions);
89
-
90
- // Wait for the confirmation that the process is successfully started, or has failed to start.
91
- await new Promise((resolve, reject) => {
92
- terminal.onStart(resolve);
93
- terminal.onError((error: ProcessErrorEvent) => {
94
- reject(ProcessTaskError.CouldNotRun(error.code));
95
- });
96
- });
97
-
98
- const processType = (taskConfig.taskType || taskConfig.type) as 'process' | 'shell';
99
- return this.taskFactory({
100
- label: taskConfig.label,
101
- process: terminal,
102
- processType,
103
- context: ctx,
104
- config: taskConfig,
105
- command: this.getCommand(processType, terminalProcessOptions)
106
- });
107
- } catch (error) {
108
- this.logger.error(`Error occurred while creating task: ${error}`);
109
- throw error;
110
- }
111
- }
112
-
113
- protected getResolvedCommand(taskConfig: TaskConfiguration): TerminalProcessOptions {
114
- const osSpecificCommand = this.getOsSpecificCommand(taskConfig);
115
-
116
- const options = osSpecificCommand.options;
117
-
118
- // Use task's cwd with spawned process and pass node env object to
119
- // new process, so e.g. we can re-use the system path
120
- if (options) {
121
- options.env = {
122
- ...process.env,
123
- ...(options.env || {})
124
- };
125
- }
126
-
127
- /** Executable to actually spawn. */
128
- let command: string;
129
- /** List of arguments passed to `command`. */
130
- let args: string[];
131
-
132
- /**
133
- * Only useful on Windows, has to do with how node-pty handles complex commands.
134
- * This string should not include the executable, only what comes after it (arguments).
135
- */
136
- let commandLine: string | undefined;
137
-
138
- if ((taskConfig.taskType || taskConfig.type) === 'shell') {
139
- // When running a shell task, we have to spawn a shell process somehow,
140
- // and tell it to run the command the user wants to run inside of it.
141
- //
142
- // E.g:
143
- // - Spawning a process:
144
- // spawn(process_exe, [...args])
145
- // - Spawning a shell and run a command:
146
- // spawn(shell_exe, [shell_exec_cmd_flag, command])
147
- //
148
- // The fun part is, the `command` to pass as an argument usually has to be
149
- // what you would type verbatim inside the shell, so escaping rules apply.
150
- //
151
- // What's even more funny is that on Windows, node-pty uses a special
152
- // mechanism to pass complex escaped arguments, via a string.
153
- //
154
- // We need to accommodate most shells, so we need to get specific.
155
-
156
- const { shell } = osSpecificCommand.options;
157
-
158
- command = shell?.executable || ShellProcess.getShellExecutablePath();
159
- const { execArgs, quotingFunctions } = this.getShellSpecificOptions(command);
160
-
161
- // Allow overriding shell options from task configuration.
162
- args = shell?.args ? [...shell.args] : [...execArgs];
163
-
164
- // Check if an argument list is defined or not. Empty is ok.
165
- /** Shell command to run: */
166
- const shellCommand = this.buildShellCommand(osSpecificCommand, quotingFunctions);
167
-
168
- if (isWindows && /cmd(.exe)?$/.test(command)) {
169
- // Let's take the following command, including an argument containing whitespace:
170
- // cmd> node -p process.argv 1 2 " 3"
171
- //
172
- // We would expect the following output:
173
- // json> [ '...\\node.exe', '1', '2', ' 3' ]
174
- //
175
- // Let's run this command through `cmd.exe` using `child_process`:
176
- // js> void childprocess.spawn('cmd.exe', ['/s', '/c', 'node -p process.argv 1 2 " 3"']).stderr.on('data', console.log)
177
- //
178
- // We get the correct output, but when using node-pty:
179
- // js> void nodepty.spawn('cmd.exe', ['/s', '/c', 'node -p process.argv 1 2 " 3"']).on('data', console.log)
180
- //
181
- // Then the output looks like:
182
- // json> [ '...\\node.exe', '1', '2', '"', '3"' ]
183
- //
184
- // To fix that, we need to use a special node-pty feature and pass arguments as one string:
185
- // js> nodepty.spawn('cmd.exe', '/s /c "node -p process.argv 1 2 " 3""')
186
- //
187
- // Note the extra quotes that need to be added around the whole command.
188
- commandLine = [...args, `"${shellCommand}"`].join(' ');
189
- }
190
-
191
- args.push(shellCommand);
192
- } else {
193
- // When running process tasks, `command` is the executable to run,
194
- // and `args` are the arguments we want to pass to it.
195
- command = osSpecificCommand.command;
196
- if (Array.isArray(osSpecificCommand.args)) {
197
- // Process task doesn't handle quotation: Normalize arguments from `ShellQuotedString` to raw `string`.
198
- args = osSpecificCommand.args.map(arg => typeof arg === 'string' ? arg : arg.value);
199
- } else {
200
- args = [];
201
- }
202
- }
203
- return { command, args, commandLine, options };
204
- }
205
-
206
- protected buildShellCommand(systemSpecificCommand: OsSpecificCommand, quotingFunctions?: ShellQuotingFunctions): string {
207
- if (Array.isArray(systemSpecificCommand.args)) {
208
- const commandLineElements: Array<string | ShellQuotedString> = [systemSpecificCommand.command, ...systemSpecificCommand.args].map(arg => {
209
- // We want to quote arguments only if needed.
210
- if (quotingFunctions && typeof arg === 'string' && this.argumentNeedsQuotes(arg, quotingFunctions)) {
211
- return {
212
- quoting: ShellQuoting.Strong,
213
- value: arg,
214
- };
215
- } else {
216
- return arg;
217
- }
218
- });
219
- return createShellCommandLine(commandLineElements, quotingFunctions);
220
- } else {
221
- // No arguments are provided, so `command` is actually the full command line to execute.
222
- return systemSpecificCommand.command ?? '';
223
- }
224
- }
225
-
226
- protected getShellSpecificOptions(command: string): ShellSpecificOptions {
227
- if (/bash(.exe)?$/.test(command)) {
228
- return {
229
- quotingFunctions: BashQuotingFunctions,
230
- execArgs: ['-c']
231
- };
232
- } else if (/wsl(.exe)?$/.test(command)) {
233
- return {
234
- quotingFunctions: BashQuotingFunctions,
235
- execArgs: ['-e']
236
- };
237
- } else if (/cmd(.exe)?$/.test(command)) {
238
- return {
239
- quotingFunctions: CmdQuotingFunctions,
240
- execArgs: ['/S', '/C']
241
- };
242
- } else if (/(ps|pwsh|powershell)(.exe)?/.test(command)) {
243
- return {
244
- quotingFunctions: PowershellQuotingFunctions,
245
- execArgs: ['-c']
246
- };
247
- } else {
248
- return {
249
- quotingFunctions: BashQuotingFunctions,
250
- execArgs: ['-l', '-c']
251
- };
252
- }
253
- }
254
-
255
- protected getOsSpecificCommand(taskConfig: TaskConfiguration): OsSpecificCommand {
256
- // on windows, windows-specific options, if available, take precedence
257
- if (isWindows && taskConfig.windows !== undefined) {
258
- return this.getSystemSpecificCommand(taskConfig, 'windows');
259
- } else if (isOSX && taskConfig.osx !== undefined) { // on macOS, mac-specific options, if available, take precedence
260
- return this.getSystemSpecificCommand(taskConfig, 'osx');
261
- } else if (!isWindows && !isOSX && taskConfig.linux !== undefined) { // on linux, linux-specific options, if available, take precedence
262
- return this.getSystemSpecificCommand(taskConfig, 'linux');
263
- } else { // system-specific options are unavailable, use the default
264
- return this.getSystemSpecificCommand(taskConfig, undefined);
265
- }
266
- }
267
-
268
- protected getCommand(processType: 'process' | 'shell', terminalProcessOptions: TerminalProcessOptions): string | undefined {
269
- if (terminalProcessOptions.args) {
270
- if (processType === 'shell') {
271
- return terminalProcessOptions.args[terminalProcessOptions.args.length - 1];
272
- } else if (processType === 'process') {
273
- return `${terminalProcessOptions.command} ${terminalProcessOptions.args.join(' ')}`;
274
- }
275
- }
276
- }
277
-
278
- /**
279
- * This is task specific, to align with VS Code's behavior.
280
- *
281
- * When parsing arguments, VS Code will try to detect if the user already
282
- * tried to quote things.
283
- *
284
- * See: https://github.com/microsoft/vscode/blob/d363b988e1e58cf49963841c498681cdc6cb55a3/src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts#L1101-L1127
285
- *
286
- * @param value
287
- * @param shellQuotingOptions
288
- */
289
- protected argumentNeedsQuotes(value: string, shellQuotingOptions: ShellQuotingFunctions): boolean {
290
- const { characters } = shellQuotingOptions;
291
- const needQuotes = new Set([' ', ...characters.needQuotes || []]);
292
- if (!characters) {
293
- return false;
294
- }
295
- if (value.length >= 2) {
296
- const first = value[0] === characters.strong ? characters.strong : value[0] === characters.weak ? characters.weak : undefined;
297
- if (first === value[value.length - 1]) {
298
- return false;
299
- }
300
- }
301
- let quote: string | undefined;
302
- for (let i = 0; i < value.length; i++) {
303
- // We found the end quote.
304
- const ch = value[i];
305
- if (ch === quote) {
306
- quote = undefined;
307
- } else if (quote !== undefined) {
308
- // skip the character. We are quoted.
309
- continue;
310
- } else if (ch === characters.escape) {
311
- // Skip the next character
312
- i++;
313
- } else if (ch === characters.strong || ch === characters.weak) {
314
- quote = ch;
315
- } else if (needQuotes.has(ch)) {
316
- return true;
317
- }
318
- }
319
- return false;
320
- }
321
-
322
- protected getSystemSpecificCommand(taskConfig: TaskConfiguration, system: 'windows' | 'linux' | 'osx' | undefined): OsSpecificCommand {
323
- // initialize with default values from the `taskConfig`
324
- let command: string | undefined = taskConfig.command;
325
- let args: Array<string | ShellQuotedString> | undefined = taskConfig.args;
326
- let options: CommandOptions = deepClone(taskConfig.options) || {};
327
-
328
- if (system) {
329
- if (taskConfig[system].command) {
330
- command = taskConfig[system].command;
331
- }
332
- if (taskConfig[system].args) {
333
- args = taskConfig[system].args;
334
- }
335
- if (taskConfig[system].options) {
336
- options = taskConfig[system].options;
337
- }
338
- }
339
-
340
- if (options.cwd) {
341
- options.cwd = this.asFsPath(options.cwd);
342
- }
343
-
344
- if (command === undefined) {
345
- throw new Error('The `command` field of a task cannot be undefined.');
346
- }
347
-
348
- return { command, args, options };
349
- }
350
-
351
- protected asFsPath(uriOrPath: string): string {
352
- return (uriOrPath.startsWith('file:'))
353
- ? FileUri.fsPath(uriOrPath)
354
- : uriOrPath;
355
- }
356
-
357
- /**
358
- * @deprecated
359
- *
360
- * Remove ProcessTaskRunner.findCommand, introduce process "started" event
361
- * Checks for the existence of a file, at the provided path, and make sure that
362
- * it's readable and executable.
363
- */
364
- protected async executableFileExists(filePath: string): Promise<boolean> {
365
- return new Promise<boolean>(async (resolve, reject) => {
366
- fs.access(filePath, fs.constants.F_OK | fs.constants.X_OK, err => {
367
- resolve(err ? false : true);
368
- });
369
- });
370
- }
371
- }
1
+ // *****************************************************************************
2
+ // Copyright (C) 2017-2019 Ericsson and others.
3
+ //
4
+ // This program and the accompanying materials are made available under the
5
+ // terms of the Eclipse Public License v. 2.0 which is available at
6
+ // http://www.eclipse.org/legal/epl-2.0.
7
+ //
8
+ // This Source Code may also be made available under the following Secondary
9
+ // Licenses when the conditions for such availability set forth in the Eclipse
10
+ // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
+ // with the GNU Classpath Exception which is available at
12
+ // https://www.gnu.org/software/classpath/license.html.
13
+ //
14
+ // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
15
+ // *****************************************************************************
16
+
17
+ /*---------------------------------------------------------------------------------------------
18
+ * Copyright (c) Microsoft Corporation. All rights reserved.
19
+ * Licensed under the MIT License. See License.txt in the project root for license information.
20
+ *--------------------------------------------------------------------------------------------*/
21
+
22
+ import { injectable, inject, named } from '@theia/core/shared/inversify';
23
+ import { deepClone, isWindows, isOSX, ILogger } from '@theia/core';
24
+ import { FileUri } from '@theia/core/lib/node';
25
+ import {
26
+ RawProcessFactory,
27
+ ProcessErrorEvent,
28
+ Process,
29
+ TerminalProcessOptions,
30
+ TaskTerminalProcessFactory,
31
+ } from '@theia/process/lib/node';
32
+ import {
33
+ ShellQuotedString, ShellQuotingFunctions, BashQuotingFunctions, CmdQuotingFunctions, PowershellQuotingFunctions, createShellCommandLine, ShellQuoting,
34
+ } from '@theia/process/lib/common/shell-quoting';
35
+ import { TaskFactory } from './process-task';
36
+ import { TaskRunner } from '../task-runner-protocol';
37
+ import { Task } from '../task';
38
+ import { TaskConfiguration } from '../../common/task-protocol';
39
+ import { ProcessTaskError, CommandOptions } from '../../common/process/task-protocol';
40
+ import * as fs from 'fs';
41
+ import { ShellProcess } from '@theia/terminal/lib/node/shell-process';
42
+
43
+ export interface OsSpecificCommand {
44
+ command: string,
45
+ args: Array<string | ShellQuotedString> | undefined,
46
+ options: CommandOptions
47
+ }
48
+
49
+ export interface ShellSpecificOptions {
50
+ /** Arguments passed to the shell, aka `command` here. */
51
+ execArgs: string[];
52
+ /** Pack of functions used to escape the `subCommand` and `subArgs` to run in the shell. */
53
+ quotingFunctions?: ShellQuotingFunctions;
54
+ }
55
+
56
+ /**
57
+ * Task runner that runs a task as a process or a command inside a shell.
58
+ */
59
+ @injectable()
60
+ export class ProcessTaskRunner implements TaskRunner {
61
+
62
+ @inject(ILogger) @named('task')
63
+ protected readonly logger: ILogger;
64
+
65
+ @inject(RawProcessFactory)
66
+ protected readonly rawProcessFactory: RawProcessFactory;
67
+
68
+ @inject(TaskTerminalProcessFactory)
69
+ protected readonly taskTerminalProcessFactory: TaskTerminalProcessFactory;
70
+
71
+ @inject(TaskFactory)
72
+ protected readonly taskFactory: TaskFactory;
73
+
74
+ /**
75
+ * Runs a task from the given task configuration.
76
+ * @param taskConfig task configuration to run a task from. The provided task configuration must have a shape of `CommandProperties`.
77
+ */
78
+ async run(taskConfig: TaskConfiguration, ctx?: string): Promise<Task> {
79
+ if (!taskConfig.command) {
80
+ throw new Error("Process task config must have 'command' property specified");
81
+ }
82
+ try {
83
+ // Always spawn a task in a pty, the only difference between shell/process tasks is the
84
+ // way the command is passed:
85
+ // - process: directly look for an executable and pass a specific set of arguments/options.
86
+ // - shell: defer the spawning to a shell that will evaluate a command line with our executable.
87
+ const terminalProcessOptions = this.getResolvedCommand(taskConfig);
88
+ const terminal: Process = this.taskTerminalProcessFactory(terminalProcessOptions);
89
+
90
+ // Wait for the confirmation that the process is successfully started, or has failed to start.
91
+ await new Promise((resolve, reject) => {
92
+ terminal.onStart(resolve);
93
+ terminal.onError((error: ProcessErrorEvent) => {
94
+ reject(ProcessTaskError.CouldNotRun(error.code));
95
+ });
96
+ });
97
+
98
+ const processType = (taskConfig.taskType || taskConfig.type) as 'process' | 'shell';
99
+ return this.taskFactory({
100
+ label: taskConfig.label,
101
+ process: terminal,
102
+ processType,
103
+ context: ctx,
104
+ config: taskConfig,
105
+ command: this.getCommand(processType, terminalProcessOptions)
106
+ });
107
+ } catch (error) {
108
+ this.logger.error(`Error occurred while creating task: ${error}`);
109
+ throw error;
110
+ }
111
+ }
112
+
113
+ protected getResolvedCommand(taskConfig: TaskConfiguration): TerminalProcessOptions {
114
+ const osSpecificCommand = this.getOsSpecificCommand(taskConfig);
115
+
116
+ const options = osSpecificCommand.options;
117
+
118
+ // Use task's cwd with spawned process and pass node env object to
119
+ // new process, so e.g. we can re-use the system path
120
+ if (options) {
121
+ options.env = {
122
+ ...process.env,
123
+ ...(options.env || {})
124
+ };
125
+ }
126
+
127
+ /** Executable to actually spawn. */
128
+ let command: string;
129
+ /** List of arguments passed to `command`. */
130
+ let args: string[];
131
+
132
+ /**
133
+ * Only useful on Windows, has to do with how node-pty handles complex commands.
134
+ * This string should not include the executable, only what comes after it (arguments).
135
+ */
136
+ let commandLine: string | undefined;
137
+
138
+ if ((taskConfig.taskType || taskConfig.type) === 'shell') {
139
+ // When running a shell task, we have to spawn a shell process somehow,
140
+ // and tell it to run the command the user wants to run inside of it.
141
+ //
142
+ // E.g:
143
+ // - Spawning a process:
144
+ // spawn(process_exe, [...args])
145
+ // - Spawning a shell and run a command:
146
+ // spawn(shell_exe, [shell_exec_cmd_flag, command])
147
+ //
148
+ // The fun part is, the `command` to pass as an argument usually has to be
149
+ // what you would type verbatim inside the shell, so escaping rules apply.
150
+ //
151
+ // What's even more funny is that on Windows, node-pty uses a special
152
+ // mechanism to pass complex escaped arguments, via a string.
153
+ //
154
+ // We need to accommodate most shells, so we need to get specific.
155
+
156
+ const { shell } = osSpecificCommand.options;
157
+
158
+ command = shell?.executable || ShellProcess.getShellExecutablePath();
159
+ const { execArgs, quotingFunctions } = this.getShellSpecificOptions(command);
160
+
161
+ // Allow overriding shell options from task configuration.
162
+ args = shell?.args ? [...shell.args] : [...execArgs];
163
+
164
+ // Check if an argument list is defined or not. Empty is ok.
165
+ /** Shell command to run: */
166
+ const shellCommand = this.buildShellCommand(osSpecificCommand, quotingFunctions);
167
+
168
+ if (isWindows && /cmd(.exe)?$/.test(command)) {
169
+ // Let's take the following command, including an argument containing whitespace:
170
+ // cmd> node -p process.argv 1 2 " 3"
171
+ //
172
+ // We would expect the following output:
173
+ // json> [ '...\\node.exe', '1', '2', ' 3' ]
174
+ //
175
+ // Let's run this command through `cmd.exe` using `child_process`:
176
+ // js> void childprocess.spawn('cmd.exe', ['/s', '/c', 'node -p process.argv 1 2 " 3"']).stderr.on('data', console.log)
177
+ //
178
+ // We get the correct output, but when using node-pty:
179
+ // js> void nodepty.spawn('cmd.exe', ['/s', '/c', 'node -p process.argv 1 2 " 3"']).on('data', console.log)
180
+ //
181
+ // Then the output looks like:
182
+ // json> [ '...\\node.exe', '1', '2', '"', '3"' ]
183
+ //
184
+ // To fix that, we need to use a special node-pty feature and pass arguments as one string:
185
+ // js> nodepty.spawn('cmd.exe', '/s /c "node -p process.argv 1 2 " 3""')
186
+ //
187
+ // Note the extra quotes that need to be added around the whole command.
188
+ commandLine = [...args, `"${shellCommand}"`].join(' ');
189
+ }
190
+
191
+ args.push(shellCommand);
192
+ } else {
193
+ // When running process tasks, `command` is the executable to run,
194
+ // and `args` are the arguments we want to pass to it.
195
+ command = osSpecificCommand.command;
196
+ if (Array.isArray(osSpecificCommand.args)) {
197
+ // Process task doesn't handle quotation: Normalize arguments from `ShellQuotedString` to raw `string`.
198
+ args = osSpecificCommand.args.map(arg => typeof arg === 'string' ? arg : arg.value);
199
+ } else {
200
+ args = [];
201
+ }
202
+ }
203
+ return { command, args, commandLine, options };
204
+ }
205
+
206
+ protected buildShellCommand(systemSpecificCommand: OsSpecificCommand, quotingFunctions?: ShellQuotingFunctions): string {
207
+ if (Array.isArray(systemSpecificCommand.args)) {
208
+ const commandLineElements: Array<string | ShellQuotedString> = [systemSpecificCommand.command, ...systemSpecificCommand.args].map(arg => {
209
+ // We want to quote arguments only if needed.
210
+ if (quotingFunctions && typeof arg === 'string' && this.argumentNeedsQuotes(arg, quotingFunctions)) {
211
+ return {
212
+ quoting: ShellQuoting.Strong,
213
+ value: arg,
214
+ };
215
+ } else {
216
+ return arg;
217
+ }
218
+ });
219
+ return createShellCommandLine(commandLineElements, quotingFunctions);
220
+ } else {
221
+ // No arguments are provided, so `command` is actually the full command line to execute.
222
+ return systemSpecificCommand.command ?? '';
223
+ }
224
+ }
225
+
226
+ protected getShellSpecificOptions(command: string): ShellSpecificOptions {
227
+ if (/bash(.exe)?$/.test(command)) {
228
+ return {
229
+ quotingFunctions: BashQuotingFunctions,
230
+ execArgs: ['-c']
231
+ };
232
+ } else if (/wsl(.exe)?$/.test(command)) {
233
+ return {
234
+ quotingFunctions: BashQuotingFunctions,
235
+ execArgs: ['-e']
236
+ };
237
+ } else if (/cmd(.exe)?$/.test(command)) {
238
+ return {
239
+ quotingFunctions: CmdQuotingFunctions,
240
+ execArgs: ['/S', '/C']
241
+ };
242
+ } else if (/(ps|pwsh|powershell)(.exe)?/.test(command)) {
243
+ return {
244
+ quotingFunctions: PowershellQuotingFunctions,
245
+ execArgs: ['-c']
246
+ };
247
+ } else {
248
+ return {
249
+ quotingFunctions: BashQuotingFunctions,
250
+ execArgs: ['-l', '-c']
251
+ };
252
+ }
253
+ }
254
+
255
+ protected getOsSpecificCommand(taskConfig: TaskConfiguration): OsSpecificCommand {
256
+ // on windows, windows-specific options, if available, take precedence
257
+ if (isWindows && taskConfig.windows !== undefined) {
258
+ return this.getSystemSpecificCommand(taskConfig, 'windows');
259
+ } else if (isOSX && taskConfig.osx !== undefined) { // on macOS, mac-specific options, if available, take precedence
260
+ return this.getSystemSpecificCommand(taskConfig, 'osx');
261
+ } else if (!isWindows && !isOSX && taskConfig.linux !== undefined) { // on linux, linux-specific options, if available, take precedence
262
+ return this.getSystemSpecificCommand(taskConfig, 'linux');
263
+ } else { // system-specific options are unavailable, use the default
264
+ return this.getSystemSpecificCommand(taskConfig, undefined);
265
+ }
266
+ }
267
+
268
+ protected getCommand(processType: 'process' | 'shell', terminalProcessOptions: TerminalProcessOptions): string | undefined {
269
+ if (terminalProcessOptions.args) {
270
+ if (processType === 'shell') {
271
+ return terminalProcessOptions.args[terminalProcessOptions.args.length - 1];
272
+ } else if (processType === 'process') {
273
+ return `${terminalProcessOptions.command} ${terminalProcessOptions.args.join(' ')}`;
274
+ }
275
+ }
276
+ }
277
+
278
+ /**
279
+ * This is task specific, to align with VS Code's behavior.
280
+ *
281
+ * When parsing arguments, VS Code will try to detect if the user already
282
+ * tried to quote things.
283
+ *
284
+ * See: https://github.com/microsoft/vscode/blob/d363b988e1e58cf49963841c498681cdc6cb55a3/src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts#L1101-L1127
285
+ *
286
+ * @param value
287
+ * @param shellQuotingOptions
288
+ */
289
+ protected argumentNeedsQuotes(value: string, shellQuotingOptions: ShellQuotingFunctions): boolean {
290
+ const { characters } = shellQuotingOptions;
291
+ const needQuotes = new Set([' ', ...characters.needQuotes || []]);
292
+ if (!characters) {
293
+ return false;
294
+ }
295
+ if (value.length >= 2) {
296
+ const first = value[0] === characters.strong ? characters.strong : value[0] === characters.weak ? characters.weak : undefined;
297
+ if (first === value[value.length - 1]) {
298
+ return false;
299
+ }
300
+ }
301
+ let quote: string | undefined;
302
+ for (let i = 0; i < value.length; i++) {
303
+ // We found the end quote.
304
+ const ch = value[i];
305
+ if (ch === quote) {
306
+ quote = undefined;
307
+ } else if (quote !== undefined) {
308
+ // skip the character. We are quoted.
309
+ continue;
310
+ } else if (ch === characters.escape) {
311
+ // Skip the next character
312
+ i++;
313
+ } else if (ch === characters.strong || ch === characters.weak) {
314
+ quote = ch;
315
+ } else if (needQuotes.has(ch)) {
316
+ return true;
317
+ }
318
+ }
319
+ return false;
320
+ }
321
+
322
+ protected getSystemSpecificCommand(taskConfig: TaskConfiguration, system: 'windows' | 'linux' | 'osx' | undefined): OsSpecificCommand {
323
+ // initialize with default values from the `taskConfig`
324
+ let command: string | undefined = taskConfig.command;
325
+ let args: Array<string | ShellQuotedString> | undefined = taskConfig.args;
326
+ let options: CommandOptions = deepClone(taskConfig.options) || {};
327
+
328
+ if (system) {
329
+ if (taskConfig[system].command) {
330
+ command = taskConfig[system].command;
331
+ }
332
+ if (taskConfig[system].args) {
333
+ args = taskConfig[system].args;
334
+ }
335
+ if (taskConfig[system].options) {
336
+ options = taskConfig[system].options;
337
+ }
338
+ }
339
+
340
+ if (options.cwd) {
341
+ options.cwd = this.asFsPath(options.cwd);
342
+ }
343
+
344
+ if (command === undefined) {
345
+ throw new Error('The `command` field of a task cannot be undefined.');
346
+ }
347
+
348
+ return { command, args, options };
349
+ }
350
+
351
+ protected asFsPath(uriOrPath: string): string {
352
+ return (uriOrPath.startsWith('file:'))
353
+ ? FileUri.fsPath(uriOrPath)
354
+ : uriOrPath;
355
+ }
356
+
357
+ /**
358
+ * @deprecated
359
+ *
360
+ * Remove ProcessTaskRunner.findCommand, introduce process "started" event
361
+ * Checks for the existence of a file, at the provided path, and make sure that
362
+ * it's readable and executable.
363
+ */
364
+ protected async executableFileExists(filePath: string): Promise<boolean> {
365
+ return new Promise<boolean>(async (resolve, reject) => {
366
+ fs.access(filePath, fs.constants.F_OK | fs.constants.X_OK, err => {
367
+ resolve(err ? false : true);
368
+ });
369
+ });
370
+ }
371
+ }