microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/utils/commands/commandExecutor.ts
68lines · 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 {ChildProcess} from "child_process"; |
| 5 | import {Log} from "./log"; |
| 6 | import {Node} from "../node/node"; |
| 7 | import {OutputChannel} from "vscode"; |
| 8 | import * as Q from "q"; |
| 9 | |
| 10 | interface EnvironmentOptions { |
| 11 | REACT_DEBUGGER?: string; |
| 12 | } |
| 13 | |
| 14 | interface Options { |
| 15 | env?: EnvironmentOptions; |
| 16 | } |
| 17 | |
| 18 | export class CommandExecutor { |
| 19 | private currentWorkingDirectory: string; |
| 20 | |
| 21 | constructor(currentWorkingDirectory?: string) { |
| 22 | this.currentWorkingDirectory = currentWorkingDirectory; |
| 23 | } |
| 24 | |
| 25 | public execute(command: string, options: Options = {}): Q.Promise<void> { |
| 26 | Log.commandStarted(command); |
| 27 | return new Node.ChildProcess().execToString(command, { cwd: this.currentWorkingDirectory, env: options.env }) |
| 28 | .then(stdout => { |
| 29 | Log.logMessage(stdout); |
| 30 | Log.commandEnded(command); |
| 31 | }, |
| 32 | reason => Log.commandFailed(command, reason)); |
| 33 | } |
| 34 | |
| 35 | public spawn(command: string, args: string[], options: Options = {}, outputChannel?: OutputChannel): Q.Promise<ChildProcess> { |
| 36 | let spawnOptions = Object.assign({}, { cwd: this.currentWorkingDirectory }, options); |
| 37 | let commandWithArgs = command + " " + args.join(" "); |
| 38 | |
| 39 | Log.commandStarted(commandWithArgs, outputChannel); |
| 40 | let result = new Node.ChildProcess().spawn(command, args, spawnOptions); |
| 41 | |
| 42 | result.stderr.on("data", (data: Buffer) => { |
| 43 | if (outputChannel) { |
| 44 | outputChannel.append(data.toString()); |
| 45 | } else { |
| 46 | process.stderr.write(data); |
| 47 | } |
| 48 | }); |
| 49 | |
| 50 | result.stdout.on("data", (data: Buffer) => { |
| 51 | if (outputChannel) { |
| 52 | outputChannel.append(data.toString()); |
| 53 | } else { |
| 54 | process.stdout.write(data); |
| 55 | } |
| 56 | }); |
| 57 | |
| 58 | result.outcome.then(() => { |
| 59 | Log.commandEnded(commandWithArgs, outputChannel); |
| 60 | }, |
| 61 | (reason) => { |
| 62 | Log.commandFailed(commandWithArgs, reason, outputChannel); |
| 63 | }); |
| 64 | |
| 65 | return Q.resolve(result.spawnedProcess); |
| 66 | } |
| 67 | |
| 68 | } |
| 69 | |