* Process the ChildProcess object created by an async command.
( command: string, options: CommonCmdOpts, childProcess: _ChildProcess, )
| 181 | */ |
| 182 | function getEnvironmentForNonInteractiveCommand( |
| 183 | userProvidedEnv?: NodeJS.ProcessEnv, |
| 184 | cwd?: string | URL, |
| 185 | ): NodeJS.ProcessEnv { |
| 186 | // Pass through the color level from the TTY/process performing the `spawn` call. |
| 187 | const forceColorValue = |
| 188 | supportsColor.stdout !== false ? supportsColor.stdout.level.toString() : undefined; |
| 189 | const sanitizedEnv = sanitizeEnvironmentPath( |
| 190 | userProvidedEnv ?? process.env, |
| 191 | getExcludedDirsForCwd(cwd), |
| 192 | ); |
| 193 | |
| 194 | return {FORCE_COLOR: forceColorValue, ...sanitizedEnv}; |
| 195 | } |
| 196 | |
| 197 | /** |
| 198 | * Process the ChildProcess object created by an async command. |
| 199 | */ |
| 200 | function processAsyncCmd( |
| 201 | command: string, |
| 202 | options: CommonCmdOpts, |
| 203 | childProcess: _ChildProcess, |
| 204 | ): Promise<SpawnResult> { |
| 205 | return new Promise((resolve, reject) => { |
| 206 | let logOutput = ''; |
| 207 | let stdout = ''; |
| 208 | let stderr = ''; |
| 209 | |
| 210 | Log.debug(`Executing command: ${sanitize(command)}`); |
| 211 | |
| 212 | childProcess.on('error', (err) => { |
| 213 | const sanitizedErr = sanitizeError(err); |
| 214 | const printFn = options.mode === 'on-error' ? Log.error : Log.debug; |
| 215 | printFn(`Command "${sanitize(command)}" failed with error: ${sanitizedErr.message}`); |
| 216 | reject(sanitizedErr); |
| 217 | }); |
| 218 | |
| 219 | // If provided, write `input` text to the process `stdin`. |
| 220 | if (options.input !== undefined) { |
| 221 | assert( |
| 222 | childProcess.stdin, |
| 223 | 'Cannot write process `input` if there is no pipe `stdin` channel.', |
| 224 | ); |
| 225 | childProcess.stdin.write(options.input); |
| 226 | childProcess.stdin.end(); |
| 227 | } |
| 228 | |
| 229 | // Capture the stdout separately so that it can be passed as resolve value. |
| 230 | // This is useful if commands return parsable stdout. |
| 231 | childProcess.stderr?.on('data', (message) => { |
| 232 | stderr += message; |
| 233 | logOutput += message; |
| 234 | // If console output is enabled, print the message directly to the stderr. Note that |
| 235 | // we intentionally print all output to stderr as stdout should not be polluted. |
| 236 | if (options.mode === undefined || options.mode === 'enabled') { |
| 237 | process.stderr.write(sanitize(String(message))); |
| 238 | } |
| 239 | }); |
| 240 |