microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
supports-bunx-as-a-react-native-package-manager

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/common/commandExecutor.ts

291lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as path from "path";
5import * as cp from "child_process";
6import * as nls from "vscode-nls";
7import { ILogger } from "../extension/log/LogHelper";
8import { NullLogger } from "../extension/log/NullLogger";
9import { ProjectVersionHelper } from "./projectVersionHelper";
10import { ISpawnResult } from "./node/childProcess";
11import { HostPlatform, HostPlatformId } from "./hostPlatform";
12import { ErrorHelper } from "./error/errorHelper";
13import { InternalErrorCode } from "./error/internalErrorCode";
14import { Node } from "./node/node";
15
16nls.config({
17 messageFormat: nls.MessageFormat.bundle,
18 bundleFormat: nls.BundleFormat.standalone,
19})();
20const localize = nls.loadMessageBundle();
21
22export enum CommandVerbosity {
23 OUTPUT,
24 SILENT,
25 PROGRESS,
26}
27
28interface EnvironmentOptions {
29 REACT_DEBUGGER?: string;
30}
31
32interface Options {
33 env?: EnvironmentOptions;
34 verbosity?: CommandVerbosity;
35 cwd?: string;
36}
37
38export enum CommandStatus {
39 Start = 0,
40 End = 1,
41}
42
43export class CommandExecutor {
44 public static ReactNativeCommand: string | null;
45 /** Set externally (e.g. from appLauncher) to the active package manager (npm/pnpm/bun). */
46 public static PackageManager: string | null;
47 private childProcess = new Node.ChildProcess();
48
49 constructor(
50 private nodeModulesRoot: string,
51 private currentWorkingDirectory: string = process.cwd(),
52 private logger: ILogger = new NullLogger(),
53 ) {}
54
55 public async execute(command: string, options: Options = {}): Promise<void> {
56 this.logger.debug(CommandExecutor.getCommandStatusString(command, CommandStatus.Start));
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 }
67 }
68
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) {
77 return reason as string;
78 }
79 }
80
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 */
88 public spawn(command: string, args: string[], options: Options = {}): Promise<any> {
89 return this.spawnChildProcess(command, args, options).outcome;
90 }
91
92 /**
93 * Spawns the React Native packager in a child process.
94 */
95 public spawnReactPackager(args: string[], options: Options = {}): ISpawnResult {
96 return this.spawnReactCommand("start", args, options);
97 }
98
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
106 public async getReactNativeVersion(): Promise<string> {
107 const versions = await ProjectVersionHelper.getReactNativeVersions(
108 this.currentWorkingDirectory,
109 );
110 return versions.reactNativeVersion;
111 }
112
113 /**
114 * Kills the React Native packager in a child process.
115 */
116 public async killReactPackager(packagerProcess?: cp.ChildProcess): Promise<void> {
117 if (packagerProcess) {
118 if (HostPlatform.getPlatformId() === HostPlatformId.WINDOWS) {
119 const res = await this.childProcess.exec(
120 `taskkill /pid ${packagerProcess.pid} /T /F`,
121 );
122 await res.outcome;
123 } else {
124 packagerProcess.kill();
125 }
126 this.logger.info(localize("PackagerStopped", "Packager stopped"));
127 } else {
128 this.logger.warning(localize("PackagerNotFound", "Packager not found"));
129 }
130 }
131
132 /**
133 * Spawns the React Native packager in a child process.
134 */
135 public spawnReactCommand(
136 command: string,
137 args: string[] = [],
138 options: Options = {},
139 ): ISpawnResult {
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 }
144 const reactCommand = HostPlatform.getNpmCliCommand(this.selectReactNativeCLI());
145 return this.spawnChildProcess(reactCommand, [command, ...args], options);
146 }
147
148 /**
149 * Spawns the Expo CLI in a child process.
150 */
151 public spawnExpoCommand(
152 command: string,
153 args: string[] = [],
154 options: Options = {},
155 ): ISpawnResult {
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 }
160 const expoCommand = HostPlatform.getNpmCliCommand(this.selectExpoCLI());
161 return this.spawnChildProcess(expoCommand, [command, ...args], options);
162 }
163
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 */
171 public async spawnWithProgress(
172 command: string,
173 args: string[],
174 options: Options = { verbosity: CommandVerbosity.OUTPUT },
175 ): Promise<void> {
176 const spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options);
177 const commandWithArgs = `${command} ${args.join(" ")}`;
178 const timeBetweenDots = 1500;
179 let lastDotTime = 0;
180
181 const printDot = () => {
182 const now = Date.now();
183 if (now - lastDotTime > timeBetweenDots) {
184 lastDotTime = now;
185 this.logger.logStream(".", process.stdout);
186 }
187 };
188
189 if (options.verbosity === CommandVerbosity.OUTPUT) {
190 this.logger.debug(
191 CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.Start),
192 );
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) {
199 this.logger.logStream(data, process.stdout);
200 } else if (options.verbosity === CommandVerbosity.PROGRESS) {
201 printDot();
202 }
203 });
204
205 result.stderr.on("data", (data: Buffer) => {
206 if (options.verbosity === CommandVerbosity.OUTPUT) {
207 this.logger.logStream(data, process.stderr);
208 } else if (options.verbosity === CommandVerbosity.PROGRESS) {
209 printDot();
210 }
211 });
212
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 }
224 }
225
226 public selectReactNativeCLI(): string {
227 return (
228 CommandExecutor.ReactNativeCommand ||
229 path.resolve(this.nodeModulesRoot, "node_modules", ".bin", "react-native")
230 );
231 }
232
233 public selectExpoCLI(): string {
234 return (
235 CommandExecutor.ReactNativeCommand ||
236 path.resolve(this.nodeModulesRoot, "node_modules", ".bin", "expo")
237 );
238 }
239
240 private spawnChildProcess(
241 command: string,
242 args: string[],
243 options: Options = {},
244 ): ISpawnResult {
245 const spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options, {
246 shell: true,
247 });
248 const commandWithArgs = `${command} ${args.join(" ")}`;
249
250 this.logger.debug(
251 CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.Start),
252 );
253 const result = this.childProcess.spawn(command, args, spawnOptions);
254
255 result.stderr.on("data", (data: Buffer) => {
256 this.logger.logStream(data, process.stderr);
257 });
258
259 result.stdout.on("data", (data: Buffer) => {
260 this.logger.logStream(data, process.stdout);
261 });
262
263 result.outcome = result.outcome.then(
264 () =>
265 this.logger.debug(
266 CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.End),
267 ),
268 reason => this.generateRejectionForCommand(commandWithArgs, reason),
269 );
270 return result;
271 }
272
273 private generateRejectionForCommand(command: string, reason: any): Promise<void> {
274 return Promise.reject<void>(
275 reason.errorCode === InternalErrorCode.CommandFailed
276 ? reason
277 : ErrorHelper.getNestedError(reason, InternalErrorCode.CommandFailed, command),
278 );
279 }
280
281 private static getCommandStatusString(command: string, status: CommandStatus) {
282 switch (status) {
283 case CommandStatus.Start:
284 return `Executing command: ${command}`;
285 case CommandStatus.End:
286 return `Finished executing: ${command}`;
287 default:
288 throw ErrorHelper.getInternalError(InternalErrorCode.UnsupportedCommandStatus);
289 }
290 }
291}