microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/common/commandExecutor.ts
291lines · modeblame
a31b007cunknown10 years ago | 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. | |
| 3 | | |
af1474acRedMickey6 years ago | 4 | import * as path from "path"; |
ce5e88eeYuri Skorokhodov6 years ago | 5 | import * as cp from "child_process"; |
09f6024fHeniker4 years ago | 6 | import * as nls from "vscode-nls"; |
34472878RedMickey5 years ago | 7 | import { ILogger } from "../extension/log/LogHelper"; |
| 8 | import { NullLogger } from "../extension/log/NullLogger"; | |
09f6024fHeniker4 years ago | 9 | import { ProjectVersionHelper } from "./projectVersionHelper"; |
34472878RedMickey5 years ago | 10 | import { ISpawnResult } from "./node/childProcess"; |
| 11 | import { HostPlatform, HostPlatformId } from "./hostPlatform"; | |
| 12 | import { ErrorHelper } from "./error/errorHelper"; | |
| 13 | import { InternalErrorCode } from "./error/internalErrorCode"; | |
ce5e88eeYuri Skorokhodov6 years ago | 14 | import { Node } from "./node/node"; |
09f6024fHeniker4 years ago | 15 | |
34472878RedMickey5 years ago | 16 | nls.config({ |
| 17 | messageFormat: nls.MessageFormat.bundle, | |
| 18 | bundleFormat: nls.BundleFormat.standalone, | |
| 19 | })(); | |
e2644f37Yuri Skorokhodov7 years ago | 20 | const localize = nls.loadMessageBundle(); |
3fb37ad5unknown10 years ago | 21 | |
831f4a85Patricio Beltran10 years ago | 22 | export enum CommandVerbosity { |
| 23 | OUTPUT, | |
| 24 | SILENT, | |
| 25 | PROGRESS, | |
| 26 | } | |
| 27 | | |
3fb37ad5unknown10 years ago | 28 | interface EnvironmentOptions { |
| 29 | REACT_DEBUGGER?: string; | |
| 30 | } | |
| 31 | | |
| 32 | interface Options { | |
| 33 | env?: EnvironmentOptions; | |
831f4a85Patricio Beltran10 years ago | 34 | verbosity?: CommandVerbosity; |
0d827d9bJimmy Thomson10 years ago | 35 | cwd?: string; |
3fb37ad5unknown10 years ago | 36 | } |
| 37 | | |
17161993Meena Kunnathur Balakrishnan10 years ago | 38 | export enum CommandStatus { |
| 39 | Start = 0, | |
27710197Vladimir Kotikov9 years ago | 40 | End = 1, |
17161993Meena Kunnathur Balakrishnan10 years ago | 41 | } |
| 42 | | |
3fb37ad5unknown10 years ago | 43 | export class CommandExecutor { |
af1474acRedMickey6 years ago | 44 | public static ReactNativeCommand: string | null; |
842deeafEmmaYuan10154 months ago | 45 | /** Set externally (e.g. from appLauncher) to the active package manager (npm/pnpm/bun). */ |
| 46 | public static PackageManager: string | null; | |
9596aa53digeff10 years ago | 47 | private childProcess = new Node.ChildProcess(); |
3fb37ad5unknown10 years ago | 48 | |
0a68f8dbArtem Egorov8 years ago | 49 | constructor( |
4dfb1c4cetatanova5 years ago | 50 | private nodeModulesRoot: string, |
0a68f8dbArtem Egorov8 years ago | 51 | private currentWorkingDirectory: string = process.cwd(), |
34472878RedMickey5 years ago | 52 | private logger: ILogger = new NullLogger(), |
| 53 | ) {} | |
3fb37ad5unknown10 years ago | 54 | |
0d77292aJiglioNero4 years ago | 55 | public async execute(command: string, options: Options = {}): Promise<void> { |
0a68f8dbArtem Egorov8 years ago | 56 | this.logger.debug(CommandExecutor.getCommandStatusString(command, CommandStatus.Start)); |
0d77292aJiglioNero4 years ago | 57 | try { |
| 58 | const stdout = await this.childProcess.execToString(command, { | |
| 59 | cwd: this.currentWorkingDirectory, | |
| 60 | env: options.env, | |
| 61 | }); | |
| 62 | this.logger.info(stdout); | |
| 63 | this.logger.debug(CommandExecutor.getCommandStatusString(command, CommandStatus.End)); | |
| 64 | } catch (reason) { | |
| 65 | return this.generateRejectionForCommand(command, reason); | |
| 66 | } | |
3fb37ad5unknown10 years ago | 67 | } |
| 68 | | |
57fee98eEzio Li3 years ago | 69 | public async executeToString(command: string, options: Options = {}): Promise<string> { |
| 70 | try { | |
| 71 | const stdout = await this.childProcess.execToString(command, { | |
| 72 | cwd: this.currentWorkingDirectory, | |
| 73 | env: options.env, | |
| 74 | }); | |
| 75 | return stdout; | |
| 76 | } catch (reason) { | |
176f99c8ConnorQi015 months ago | 77 | return reason as string; |
57fee98eEzio Li3 years ago | 78 | } |
| 79 | } | |
| 80 | | |
45944d15Meena Kunnathur Balakrishnan10 years ago | 81 | /** |
| 82 | * Spawns a child process with the params passed | |
| 83 | * This method waits until the spawned process finishes execution | |
| 84 | * {command} - The command to be invoked in the child process | |
| 85 | * {args} - Arguments to be passed to the command | |
| 86 | * {options} - additional options with which the child process needs to be spawned | |
| 87 | */ | |
ce5e88eeYuri Skorokhodov6 years ago | 88 | public spawn(command: string, args: string[], options: Options = {}): Promise<any> { |
9596aa53digeff10 years ago | 89 | return this.spawnChildProcess(command, args, options).outcome; |
45944d15Meena Kunnathur Balakrishnan10 years ago | 90 | } |
| 91 | | |
6126d899Meena Kunnathur Balakrishnan10 years ago | 92 | /** |
| 93 | * Spawns the React Native packager in a child process. | |
| 94 | */ | |
9596aa53digeff10 years ago | 95 | public spawnReactPackager(args: string[], options: Options = {}): ISpawnResult { |
| 96 | return this.spawnReactCommand("start", args, options); | |
6126d899Meena Kunnathur Balakrishnan10 years ago | 97 | } |
| 98 | | |
efb84653Ezio Li3 years ago | 99 | /** |
| 100 | * Spawns the React Native packager in a child process. | |
| 101 | */ | |
| 102 | public spawnExpoPackager(args: string[], options: Options = {}): ISpawnResult { | |
| 103 | return this.spawnExpoCommand("start", args, options); | |
| 104 | } | |
| 105 | | |
0d77292aJiglioNero4 years ago | 106 | public async getReactNativeVersion(): Promise<string> { |
| 107 | const versions = await ProjectVersionHelper.getReactNativeVersions( | |
| 108 | this.currentWorkingDirectory, | |
34472878RedMickey5 years ago | 109 | ); |
0d77292aJiglioNero4 years ago | 110 | return versions.reactNativeVersion; |
b8a56999Patricio Beltran10 years ago | 111 | } |
| 112 | | |
c3a987a7Meena Kunnathur Balakrishnan10 years ago | 113 | /** |
| 114 | * Kills the React Native packager in a child process. | |
| 115 | */ | |
0d77292aJiglioNero4 years ago | 116 | public async killReactPackager(packagerProcess?: cp.ChildProcess): Promise<void> { |
c9b4fa6cMeena Kunnathur Balakrishnan10 years ago | 117 | if (packagerProcess) { |
0d77292aJiglioNero4 years ago | 118 | if (HostPlatform.getPlatformId() === HostPlatformId.WINDOWS) { |
| 119 | const res = await this.childProcess.exec( | |
09f6024fHeniker4 years ago | 120 | `taskkill /pid ${packagerProcess.pid} /T /F`, |
0d77292aJiglioNero4 years ago | 121 | ); |
| 122 | await res.outcome; | |
| 123 | } else { | |
| 124 | packagerProcess.kill(); | |
| 125 | } | |
| 126 | this.logger.info(localize("PackagerStopped", "Packager stopped")); | |
c3a987a7Meena Kunnathur Balakrishnan10 years ago | 127 | } else { |
e2644f37Yuri Skorokhodov7 years ago | 128 | this.logger.warning(localize("PackagerNotFound", "Packager not found")); |
c3a987a7Meena Kunnathur Balakrishnan10 years ago | 129 | } |
| 130 | } | |
| 131 | | |
f8d32439dlebu10 years ago | 132 | /** |
842deeafEmmaYuan10154 months ago | 133 | * Spawns the React Native packager in a child process. |
f8d32439dlebu10 years ago | 134 | */ |
34472878RedMickey5 years ago | 135 | public spawnReactCommand( |
| 136 | command: string, | |
| 137 | args: string[] = [], | |
| 138 | options: Options = {}, | |
| 139 | ): ISpawnResult { | |
842deeafEmmaYuan10154 months ago | 140 | if (CommandExecutor.PackageManager === "bun") { |
| 141 | // bun uses `bunx` (equivalent of npx) to run CLIs. | |
| 142 | return this.spawnChildProcess("bunx", ["react-native", command, ...args], options); | |
| 143 | } | |
af1474acRedMickey6 years ago | 144 | const reactCommand = HostPlatform.getNpmCliCommand(this.selectReactNativeCLI()); |
94cd5149Artem Egorov9 years ago | 145 | return this.spawnChildProcess(reactCommand, [command, ...args], options); |
5b0582f3digeff10 years ago | 146 | } |
| 147 | | |
efb84653Ezio Li3 years ago | 148 | /** |
842deeafEmmaYuan10154 months ago | 149 | * Spawns the Expo CLI in a child process. |
efb84653Ezio Li3 years ago | 150 | */ |
| 151 | public spawnExpoCommand( | |
| 152 | command: string, | |
| 153 | args: string[] = [], | |
| 154 | options: Options = {}, | |
| 155 | ): ISpawnResult { | |
842deeafEmmaYuan10154 months ago | 156 | if (CommandExecutor.PackageManager === "bun") { |
| 157 | // bun uses `bunx expo` instead of the local .bin/expo shim. | |
| 158 | return this.spawnChildProcess("bunx", ["expo", command, ...args], options); | |
| 159 | } | |
efb84653Ezio Li3 years ago | 160 | const expoCommand = HostPlatform.getNpmCliCommand(this.selectExpoCLI()); |
| 161 | return this.spawnChildProcess(expoCommand, [command, ...args], options); | |
| 162 | } | |
| 163 | | |
831f4a85Patricio Beltran10 years ago | 164 | /** |
| 165 | * Spawns a child process with the params passed | |
| 166 | * This method has logic to do while the command is executing | |
| 167 | * {command} - The command to be invoked in the child process | |
| 168 | * {args} - Arguments to be passed to the command | |
| 169 | * {options} - additional options with which the child process needs to be spawned | |
| 170 | */ | |
0d77292aJiglioNero4 years ago | 171 | public async spawnWithProgress( |
34472878RedMickey5 years ago | 172 | command: string, |
| 173 | args: string[], | |
| 174 | options: Options = { verbosity: CommandVerbosity.OUTPUT }, | |
| 175 | ): Promise<void> { | |
831f4a85Patricio Beltran10 years ago | 176 | const spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options); |
09f6024fHeniker4 years ago | 177 | const commandWithArgs = `${command} ${args.join(" ")}`; |
831f4a85Patricio Beltran10 years ago | 178 | const timeBetweenDots = 1500; |
b0af599cJimmy Thomson10 years ago | 179 | let lastDotTime = 0; |
831f4a85Patricio Beltran10 years ago | 180 | |
| 181 | const printDot = () => { | |
b0af599cJimmy Thomson10 years ago | 182 | const now = Date.now(); |
| 183 | if (now - lastDotTime > timeBetweenDots) { | |
| 184 | lastDotTime = now; | |
0a68f8dbArtem Egorov8 years ago | 185 | this.logger.logStream(".", process.stdout); |
b0af599cJimmy Thomson10 years ago | 186 | } |
831f4a85Patricio Beltran10 years ago | 187 | }; |
| 188 | | |
| 189 | if (options.verbosity === CommandVerbosity.OUTPUT) { | |
34472878RedMickey5 years ago | 190 | this.logger.debug( |
| 191 | CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.Start), | |
| 192 | ); | |
831f4a85Patricio Beltran10 years ago | 193 | } |
| 194 | | |
| 195 | const result = this.childProcess.spawn(command, args, spawnOptions); | |
| 196 | | |
| 197 | result.stdout.on("data", (data: Buffer) => { | |
| 198 | if (options.verbosity === CommandVerbosity.OUTPUT) { | |
0a68f8dbArtem Egorov8 years ago | 199 | this.logger.logStream(data, process.stdout); |
b0af599cJimmy Thomson10 years ago | 200 | } else if (options.verbosity === CommandVerbosity.PROGRESS) { |
831f4a85Patricio Beltran10 years ago | 201 | printDot(); |
| 202 | } | |
| 203 | }); | |
| 204 | | |
| 205 | result.stderr.on("data", (data: Buffer) => { | |
| 206 | if (options.verbosity === CommandVerbosity.OUTPUT) { | |
0a68f8dbArtem Egorov8 years ago | 207 | this.logger.logStream(data, process.stderr); |
b0af599cJimmy Thomson10 years ago | 208 | } else if (options.verbosity === CommandVerbosity.PROGRESS) { |
831f4a85Patricio Beltran10 years ago | 209 | printDot(); |
| 210 | } | |
| 211 | }); | |
| 212 | | |
0d77292aJiglioNero4 years ago | 213 | try { |
| 214 | await result.outcome; | |
| 215 | if (options.verbosity === CommandVerbosity.OUTPUT) { | |
| 216 | this.logger.debug( | |
| 217 | CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.End), | |
| 218 | ); | |
| 219 | } | |
| 220 | this.logger.logStream("\n", process.stdout); | |
| 221 | } catch (reason) { | |
| 222 | return this.generateRejectionForCommand(commandWithArgs, reason); | |
| 223 | } | |
831f4a85Patricio Beltran10 years ago | 224 | } |
| 225 | | |
af1474acRedMickey6 years ago | 226 | public selectReactNativeCLI(): string { |
34472878RedMickey5 years ago | 227 | return ( |
| 228 | CommandExecutor.ReactNativeCommand || | |
4dfb1c4cetatanova5 years ago | 229 | path.resolve(this.nodeModulesRoot, "node_modules", ".bin", "react-native") |
34472878RedMickey5 years ago | 230 | ); |
af1474acRedMickey6 years ago | 231 | } |
| 232 | | |
efb84653Ezio Li3 years ago | 233 | public selectExpoCLI(): string { |
| 234 | return ( | |
| 235 | CommandExecutor.ReactNativeCommand || | |
| 236 | path.resolve(this.nodeModulesRoot, "node_modules", ".bin", "expo") | |
| 237 | ); | |
| 238 | } | |
| 239 | | |
34472878RedMickey5 years ago | 240 | private spawnChildProcess( |
| 241 | command: string, | |
| 242 | args: string[], | |
| 243 | options: Options = {}, | |
| 244 | ): ISpawnResult { | |
77e86943lexie0112 years ago | 245 | const spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options, { |
| 246 | shell: true, | |
| 247 | }); | |
09f6024fHeniker4 years ago | 248 | const commandWithArgs = `${command} ${args.join(" ")}`; |
3fb37ad5unknown10 years ago | 249 | |
34472878RedMickey5 years ago | 250 | this.logger.debug( |
| 251 | CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.Start), | |
| 252 | ); | |
9596aa53digeff10 years ago | 253 | const result = this.childProcess.spawn(command, args, spawnOptions); |
3fb37ad5unknown10 years ago | 254 | |
| 255 | result.stderr.on("data", (data: Buffer) => { | |
0a68f8dbArtem Egorov8 years ago | 256 | this.logger.logStream(data, process.stderr); |
3fb37ad5unknown10 years ago | 257 | }); |
| 258 | | |
| 259 | result.stdout.on("data", (data: Buffer) => { | |
0a68f8dbArtem Egorov8 years ago | 260 | this.logger.logStream(data, process.stdout); |
3fb37ad5unknown10 years ago | 261 | }); |
| 262 | | |
10873e11digeff10 years ago | 263 | result.outcome = result.outcome.then( |
9596aa53digeff10 years ago | 264 | () => |
34472878RedMickey5 years ago | 265 | this.logger.debug( |
| 266 | CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.End), | |
| 267 | ), | |
| 268 | reason => this.generateRejectionForCommand(commandWithArgs, reason), | |
| 269 | ); | |
efa076b0Meena Kunnathur Balakrishnan10 years ago | 270 | return result; |
3fb37ad5unknown10 years ago | 271 | } |
10873e11digeff10 years ago | 272 | |
ce5e88eeYuri Skorokhodov6 years ago | 273 | private generateRejectionForCommand(command: string, reason: any): Promise<void> { |
34472878RedMickey5 years ago | 274 | return Promise.reject<void>( |
60ad4ec0JiglioNero5 years ago | 275 | reason.errorCode === InternalErrorCode.CommandFailed |
| 276 | ? reason | |
| 277 | : ErrorHelper.getNestedError(reason, InternalErrorCode.CommandFailed, command), | |
34472878RedMickey5 years ago | 278 | ); |
10873e11digeff10 years ago | 279 | } |
0a68f8dbArtem Egorov8 years ago | 280 | |
| 281 | private static getCommandStatusString(command: string, status: CommandStatus) { | |
| 282 | switch (status) { | |
| 283 | case CommandStatus.Start: | |
fc602bb6Yuri Skorokhodov7 years ago | 284 | return `Executing command: ${command}`; |
0a68f8dbArtem Egorov8 years ago | 285 | case CommandStatus.End: |
fc602bb6Yuri Skorokhodov7 years ago | 286 | return `Finished executing: ${command}`; |
0a68f8dbArtem Egorov8 years ago | 287 | default: |
fc602bb6Yuri Skorokhodov7 years ago | 288 | throw ErrorHelper.getInternalError(InternalErrorCode.UnsupportedCommandStatus); |
0a68f8dbArtem Egorov8 years ago | 289 | } |
| 290 | } | |
3fb37ad5unknown10 years ago | 291 | } |