microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/common/commandExecutor.ts
213lines · 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 | |
| 4 | import * as path from "path"; |
| 5 | import * as cp from "child_process"; |
| 6 | import {ILogger} from "../extension/log/LogHelper"; |
| 7 | import {NullLogger} from "../extension/log/NullLogger"; |
| 8 | import {ProjectVersionHelper} from "../common/projectVersionHelper"; |
| 9 | import {ISpawnResult} from "./node/childProcess"; |
| 10 | import {HostPlatform, HostPlatformId} from "./hostPlatform"; |
| 11 | import {ErrorHelper} from "./error/errorHelper"; |
| 12 | import {InternalErrorCode} from "./error/internalErrorCode"; |
| 13 | import * as nls from "vscode-nls"; |
| 14 | import { Node } from "./node/node"; |
| 15 | nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(); |
| 16 | const localize = nls.loadMessageBundle(); |
| 17 | |
| 18 | export enum CommandVerbosity { |
| 19 | OUTPUT, |
| 20 | SILENT, |
| 21 | PROGRESS, |
| 22 | } |
| 23 | |
| 24 | interface EnvironmentOptions { |
| 25 | REACT_DEBUGGER?: string; |
| 26 | } |
| 27 | |
| 28 | interface Options { |
| 29 | env?: EnvironmentOptions; |
| 30 | verbosity?: CommandVerbosity; |
| 31 | cwd?: string; |
| 32 | } |
| 33 | |
| 34 | export enum CommandStatus { |
| 35 | Start = 0, |
| 36 | End = 1, |
| 37 | } |
| 38 | |
| 39 | export 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 = {}): 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 = {}): 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(): Promise<string> { |
| 79 | return ProjectVersionHelper.getReactNativeVersions(this.currentWorkingDirectory) |
| 80 | .then(versions => versions.reactNativeVersion); |
| 81 | } |
| 82 | |
| 83 | /** |
| 84 | * Kills the React Native packager in a child process. |
| 85 | */ |
| 86 | public killReactPackager(packagerProcess?: cp.ChildProcess): Promise<void> { |
| 87 | if (packagerProcess) { |
| 88 | return new Promise((resolve) => { |
| 89 | if (HostPlatform.getPlatformId() === HostPlatformId.WINDOWS) { |
| 90 | return resolve(this.childProcess.exec("taskkill /pid " + packagerProcess.pid + " /T /F").then((res) => res.outcome)); |
| 91 | } else { |
| 92 | packagerProcess.kill(); |
| 93 | return resolve(); |
| 94 | } |
| 95 | }).then(() => { |
| 96 | this.logger.info(localize("PackagerStopped", "Packager stopped")); |
| 97 | }); |
| 98 | |
| 99 | } else { |
| 100 | this.logger.warning(localize("PackagerNotFound", "Packager not found")); |
| 101 | return Promise.resolve(); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | /** |
| 106 | * Executes a react native command and waits for its completion. |
| 107 | */ |
| 108 | public spawnReactCommand(command: string, args: string[] = [], options: Options = {}): ISpawnResult { |
| 109 | const reactCommand = HostPlatform.getNpmCliCommand(this.selectReactNativeCLI()); |
| 110 | return this.spawnChildProcess(reactCommand, [command, ...args], options); |
| 111 | } |
| 112 | |
| 113 | /** |
| 114 | * Spawns a child process with the params passed |
| 115 | * This method has logic to do while the command is executing |
| 116 | * {command} - The command to be invoked in the child process |
| 117 | * {args} - Arguments to be passed to the command |
| 118 | * {options} - additional options with which the child process needs to be spawned |
| 119 | */ |
| 120 | public spawnWithProgress(command: string, args: string[], options: Options = { verbosity: CommandVerbosity.OUTPUT }): Promise<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 | return new Promise((resolve, reject) => { |
| 157 | result.outcome = result.outcome.then( |
| 158 | () => { |
| 159 | if (options.verbosity === CommandVerbosity.OUTPUT) { |
| 160 | this.logger.debug(CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.End)); |
| 161 | } |
| 162 | this.logger.logStream("\n", process.stdout); |
| 163 | resolve(); |
| 164 | }, |
| 165 | reason => { |
| 166 | reject(reason); |
| 167 | return this.generateRejectionForCommand(commandWithArgs, reason); |
| 168 | }); |
| 169 | }); |
| 170 | } |
| 171 | |
| 172 | public selectReactNativeCLI(): string { |
| 173 | return CommandExecutor.ReactNativeCommand || path.resolve(this.currentWorkingDirectory, "node_modules", ".bin", "react-native"); |
| 174 | } |
| 175 | |
| 176 | private spawnChildProcess(command: string, args: string[], options: Options = {}): ISpawnResult { |
| 177 | const spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options); |
| 178 | const commandWithArgs = command + " " + args.join(" "); |
| 179 | |
| 180 | this.logger.debug(CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.Start)); |
| 181 | const result = this.childProcess.spawn(command, args, spawnOptions); |
| 182 | |
| 183 | result.stderr.on("data", (data: Buffer) => { |
| 184 | this.logger.logStream(data, process.stderr); |
| 185 | }); |
| 186 | |
| 187 | result.stdout.on("data", (data: Buffer) => { |
| 188 | this.logger.logStream(data, process.stdout); |
| 189 | }); |
| 190 | |
| 191 | result.outcome = result.outcome.then( |
| 192 | () => |
| 193 | this.logger.debug(CommandExecutor.getCommandStatusString(commandWithArgs, CommandStatus.End)), |
| 194 | reason => |
| 195 | this.generateRejectionForCommand(commandWithArgs, reason)); |
| 196 | return result; |
| 197 | } |
| 198 | |
| 199 | private generateRejectionForCommand(command: string, reason: any): Promise<void> { |
| 200 | return Promise.reject<void>(ErrorHelper.getNestedError(reason, InternalErrorCode.CommandFailed, command)); |
| 201 | } |
| 202 | |
| 203 | private static getCommandStatusString(command: string, status: CommandStatus) { |
| 204 | switch (status) { |
| 205 | case CommandStatus.Start: |
| 206 | return `Executing command: ${command}`; |
| 207 | case CommandStatus.End: |
| 208 | return `Finished executing: ${command}`; |
| 209 | default: |
| 210 | throw ErrorHelper.getInternalError(InternalErrorCode.UnsupportedCommandStatus); |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | |