microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
70cfd5650973cc6872aaae01ea2db7a924e6b67b

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/common/commandExecutor.ts

212lines · 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 Q from "q";
5import * as path from "path";
6import {ChildProcess} from "child_process";
7import {ILogger} from "../extension/log/LogHelper";
8import {NullLogger} from "../extension/log/NullLogger";
9import {ReactNativeProjectHelper} from "../common/reactNativeProjectHelper";
10import {Node} from "./node/node";
11import {ISpawnResult} from "./node/childProcess";
12import {HostPlatform, HostPlatformId} from "./hostPlatform";
13import {ErrorHelper} from "./error/errorHelper";
14import {InternalErrorCode} from "./error/internalErrorCode";
15import * as nls from "vscode-nls";
16const localize = nls.loadMessageBundle();
17
18export enum CommandVerbosity {
19 OUTPUT,
20 SILENT,
21 PROGRESS,
22}
23
24interface EnvironmentOptions {
25 REACT_DEBUGGER?: string;
26}
27
28interface Options {
29 env?: EnvironmentOptions;
30 verbosity?: CommandVerbosity;
31 cwd?: string;
32}
33
34export enum CommandStatus {
35 Start = 0,
36 End = 1,
37}
38
39export class CommandExecutor {
40
41 public static ReactNativeCommand: string | null;
42 private childProcess = new Node.ChildProcess();
43
44 constructor(
45 private currentWorkingDirectory: string = process.cwd(),
46 private logger: ILogger = new NullLogger()
47 ) { }
48
49 public execute(command: string, options: Options = {}): Q.Promise<void> {
50 this.logger.debug(CommandExecutor.getCommandStatusString(command, CommandStatus.Start));
51 return this.childProcess.execToString(command, { cwd: this.currentWorkingDirectory, env: options.env })
52 .then(stdout => {
53 this.logger.info(stdout);
54 this.logger.debug(CommandExecutor.getCommandStatusString(command, CommandStatus.End));
55 },
56 (reason: Error) =>
57 this.generateRejectionForCommand(command, reason));
58 }
59
60 /**
61 * Spawns a child process with the params passed
62 * This method waits until the spawned process finishes execution
63 * {command} - The command to be invoked in the child process
64 * {args} - Arguments to be passed to the command
65 * {options} - additional options with which the child process needs to be spawned
66 */
67 public spawn(command: string, args: string[], options: Options = {}): Q.Promise<any> {
68 return this.spawnChildProcess(command, args, options).outcome;
69 }
70
71 /**
72 * Spawns the React Native packager in a child process.
73 */
74 public spawnReactPackager(args: string[], options: Options = {}): ISpawnResult {
75 return this.spawnReactCommand("start", args, options);
76 }
77
78 public getReactNativeVersion(): Q.Promise<string> {
79 return ReactNativeProjectHelper.getReactNativeVersion(this.currentWorkingDirectory);
80 }
81
82 /**
83 * Kills the React Native packager in a child process.
84 */
85 public killReactPackager(packagerProcess?: ChildProcess): Q.Promise<void> {
86 if (packagerProcess) {
87 return Q({}).then(() => {
88 if (HostPlatform.getPlatformId() === HostPlatformId.WINDOWS) {
89 return this.childProcess.exec("taskkill /pid " + packagerProcess.pid + " /T /F").outcome;
90 } else {
91 packagerProcess.kill();
92 return Q.resolve(void 0);
93 }
94 }).then(() => {
95 this.logger.info(localize("PackagerStopped", "Packager stopped"));
96 });
97
98 } else {
99 this.logger.warning(localize("PackagerNotFound", "Packager not found"));
100 return Q.resolve<void>(void 0);
101 }
102 }
103
104 /**
105 * Executes a react native command and waits for its completion.
106 */
107 public spawnReactCommand(command: string, args: string[] = [], options: Options = {}): ISpawnResult {
108 const reactCommand = HostPlatform.getNpmCliCommand(this.selectReactNativeCLI());
109 return this.spawnChildProcess(reactCommand, [command, ...args], options);
110 }
111
112 /**
113 * Spawns a child process with the params passed
114 * This method has logic to do while the command is executing
115 * {command} - The command to be invoked in the child process
116 * {args} - Arguments to be passed to the command
117 * {options} - additional options with which the child process needs to be spawned
118 */
119 public spawnWithProgress(command: string, args: string[], options: Options = { verbosity: CommandVerbosity.OUTPUT }): Q.Promise<void> {
120 let deferred = Q.defer<void>();
121 const spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options);
122 const commandWithArgs = command + " " + args.join(" ");
123 const timeBetweenDots = 1500;
124 let lastDotTime = 0;
125
126 const printDot = () => {
127 const now = Date.now();
128 if (now - lastDotTime > timeBetweenDots) {
129 lastDotTime = now;
130 this.logger.logStream(".", process.stdout);
131 }
132 };
133
134 if (options.verbosity === CommandVerbosity.OUTPUT) {
135 this.logger.debug(CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.Start));
136 }
137
138 const result = this.childProcess.spawn(command, args, spawnOptions);
139
140 result.stdout.on("data", (data: Buffer) => {
141 if (options.verbosity === CommandVerbosity.OUTPUT) {
142 this.logger.logStream(data, process.stdout);
143 } else if (options.verbosity === CommandVerbosity.PROGRESS) {
144 printDot();
145 }
146 });
147
148 result.stderr.on("data", (data: Buffer) => {
149 if (options.verbosity === CommandVerbosity.OUTPUT) {
150 this.logger.logStream(data, process.stderr);
151 } else if (options.verbosity === CommandVerbosity.PROGRESS) {
152 printDot();
153 }
154 });
155
156 result.outcome = result.outcome.then(
157 () => {
158 if (options.verbosity === CommandVerbosity.OUTPUT) {
159 this.logger.debug(CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.End));
160 }
161 this.logger.logStream("\n", process.stdout);
162 deferred.resolve(void 0);
163 },
164 reason => {
165 deferred.reject(reason);
166 return this.generateRejectionForCommand(commandWithArgs, reason);
167 });
168 return deferred.promise;
169 }
170
171 public selectReactNativeCLI(): string {
172 return CommandExecutor.ReactNativeCommand || path.resolve(this.currentWorkingDirectory, "node_modules", ".bin", "react-native");
173 }
174
175 private spawnChildProcess(command: string, args: string[], options: Options = {}): ISpawnResult {
176 const spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options);
177 const commandWithArgs = command + " " + args.join(" ");
178
179 this.logger.debug(CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.Start));
180 const result = this.childProcess.spawn(command, args, spawnOptions);
181
182 result.stderr.on("data", (data: Buffer) => {
183 this.logger.logStream(data, process.stderr);
184 });
185
186 result.stdout.on("data", (data: Buffer) => {
187 this.logger.logStream(data, process.stdout);
188 });
189
190 result.outcome = result.outcome.then(
191 () =>
192 this.logger.debug(CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.End)),
193 reason =>
194 this.generateRejectionForCommand(commandWithArgs, reason));
195 return result;
196 }
197
198 private generateRejectionForCommand(command: string, reason: any): Q.Promise<void> {
199 return Q.reject<void>(ErrorHelper.getNestedError(reason, InternalErrorCode.CommandFailed, command));
200 }
201
202 private static getCommandStatusString(command: string, status: CommandStatus) {
203 switch (status) {
204 case CommandStatus.Start:
205 return `Executing command: ${command}`;
206 case CommandStatus.End:
207 return `Finished executing: ${command}`;
208 default:
209 throw ErrorHelper.getInternalError(InternalErrorCode.UnsupportedCommandStatus);
210 }
211 }
212}
213