microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1.11.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/common/commandExecutor.ts

253lines · 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 private childProcess = new Node.ChildProcess();
46
47 constructor(
48 private nodeModulesRoot: string,
49 private currentWorkingDirectory: string = process.cwd(),
50 private logger: ILogger = new NullLogger(),
51 ) {}
52
53 public async execute(command: string, options: Options = {}): Promise<void> {
54 this.logger.debug(CommandExecutor.getCommandStatusString(command, CommandStatus.Start));
55 try {
56 const stdout = await this.childProcess.execToString(command, {
57 cwd: this.currentWorkingDirectory,
58 env: options.env,
59 });
60 this.logger.info(stdout);
61 this.logger.debug(CommandExecutor.getCommandStatusString(command, CommandStatus.End));
62 } catch (reason) {
63 return this.generateRejectionForCommand(command, reason);
64 }
65 }
66
67 public async executeToString(command: string, options: Options = {}): Promise<string> {
68 try {
69 const stdout = await this.childProcess.execToString(command, {
70 cwd: this.currentWorkingDirectory,
71 env: options.env,
72 });
73 return stdout;
74 } catch (reason) {
75 return reason;
76 }
77 }
78
79 /**
80 * Spawns a child process with the params passed
81 * This method waits until the spawned process finishes execution
82 * {command} - The command to be invoked in the child process
83 * {args} - Arguments to be passed to the command
84 * {options} - additional options with which the child process needs to be spawned
85 */
86 public spawn(command: string, args: string[], options: Options = {}): Promise<any> {
87 return this.spawnChildProcess(command, args, options).outcome;
88 }
89
90 /**
91 * Spawns the React Native packager in a child process.
92 */
93 public spawnReactPackager(args: string[], options: Options = {}): ISpawnResult {
94 return this.spawnReactCommand("start", args, options);
95 }
96
97 public async getReactNativeVersion(): Promise<string> {
98 const versions = await ProjectVersionHelper.getReactNativeVersions(
99 this.currentWorkingDirectory,
100 );
101 return versions.reactNativeVersion;
102 }
103
104 /**
105 * Kills the React Native packager in a child process.
106 */
107 public async killReactPackager(packagerProcess?: cp.ChildProcess): Promise<void> {
108 if (packagerProcess) {
109 if (HostPlatform.getPlatformId() === HostPlatformId.WINDOWS) {
110 const res = await this.childProcess.exec(
111 `taskkill /pid ${packagerProcess.pid} /T /F`,
112 );
113 await res.outcome;
114 } else {
115 packagerProcess.kill();
116 }
117 this.logger.info(localize("PackagerStopped", "Packager stopped"));
118 } else {
119 this.logger.warning(localize("PackagerNotFound", "Packager not found"));
120 }
121 }
122
123 /**
124 * Executes a react native command and waits for its completion.
125 */
126 public spawnReactCommand(
127 command: string,
128 args: string[] = [],
129 options: Options = {},
130 ): ISpawnResult {
131 const reactCommand = HostPlatform.getNpmCliCommand(this.selectReactNativeCLI());
132 return this.spawnChildProcess(reactCommand, [command, ...args], options);
133 }
134
135 /**
136 * Spawns a child process with the params passed
137 * This method has logic to do while the command is executing
138 * {command} - The command to be invoked in the child process
139 * {args} - Arguments to be passed to the command
140 * {options} - additional options with which the child process needs to be spawned
141 */
142 public async spawnWithProgress(
143 command: string,
144 args: string[],
145 options: Options = { verbosity: CommandVerbosity.OUTPUT },
146 ): Promise<void> {
147 const spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options);
148 const commandWithArgs = `${command} ${args.join(" ")}`;
149 const timeBetweenDots = 1500;
150 let lastDotTime = 0;
151
152 const printDot = () => {
153 const now = Date.now();
154 if (now - lastDotTime > timeBetweenDots) {
155 lastDotTime = now;
156 this.logger.logStream(".", process.stdout);
157 }
158 };
159
160 if (options.verbosity === CommandVerbosity.OUTPUT) {
161 this.logger.debug(
162 CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.Start),
163 );
164 }
165
166 const result = this.childProcess.spawn(command, args, spawnOptions);
167
168 result.stdout.on("data", (data: Buffer) => {
169 if (options.verbosity === CommandVerbosity.OUTPUT) {
170 this.logger.logStream(data, process.stdout);
171 } else if (options.verbosity === CommandVerbosity.PROGRESS) {
172 printDot();
173 }
174 });
175
176 result.stderr.on("data", (data: Buffer) => {
177 if (options.verbosity === CommandVerbosity.OUTPUT) {
178 this.logger.logStream(data, process.stderr);
179 } else if (options.verbosity === CommandVerbosity.PROGRESS) {
180 printDot();
181 }
182 });
183
184 try {
185 await result.outcome;
186 if (options.verbosity === CommandVerbosity.OUTPUT) {
187 this.logger.debug(
188 CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.End),
189 );
190 }
191 this.logger.logStream("\n", process.stdout);
192 } catch (reason) {
193 return this.generateRejectionForCommand(commandWithArgs, reason);
194 }
195 }
196
197 public selectReactNativeCLI(): string {
198 return (
199 CommandExecutor.ReactNativeCommand ||
200 path.resolve(this.nodeModulesRoot, "node_modules", ".bin", "react-native")
201 );
202 }
203
204 private spawnChildProcess(
205 command: string,
206 args: string[],
207 options: Options = {},
208 ): ISpawnResult {
209 const spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options);
210 const commandWithArgs = `${command} ${args.join(" ")}`;
211
212 this.logger.debug(
213 CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.Start),
214 );
215 const result = this.childProcess.spawn(command, args, spawnOptions);
216
217 result.stderr.on("data", (data: Buffer) => {
218 this.logger.logStream(data, process.stderr);
219 });
220
221 result.stdout.on("data", (data: Buffer) => {
222 this.logger.logStream(data, process.stdout);
223 });
224
225 result.outcome = result.outcome.then(
226 () =>
227 this.logger.debug(
228 CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.End),
229 ),
230 reason => this.generateRejectionForCommand(commandWithArgs, reason),
231 );
232 return result;
233 }
234
235 private generateRejectionForCommand(command: string, reason: any): Promise<void> {
236 return Promise.reject<void>(
237 reason.errorCode === InternalErrorCode.CommandFailed
238 ? reason
239 : ErrorHelper.getNestedError(reason, InternalErrorCode.CommandFailed, command),
240 );
241 }
242
243 private static getCommandStatusString(command: string, status: CommandStatus) {
244 switch (status) {
245 case CommandStatus.Start:
246 return `Executing command: ${command}`;
247 case CommandStatus.End:
248 return `Finished executing: ${command}`;
249 default:
250 throw ErrorHelper.getInternalError(InternalErrorCode.UnsupportedCommandStatus);
251 }
252 }
253}
254