From 564a37a0128cf8e55b79e260bb12f74d470eeb0d Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Fri, 19 Jul 2024 17:04:15 -0400 Subject: [PATCH] Use `execFile` rather than `spawn` (#544) ## Summary Recommended in #539. --- src/common/server.ts | 31 +++++++------------------------ 1 file changed, 7 insertions(+), 24 deletions(-) diff --git a/src/common/server.ts b/src/common/server.ts index e282892..b8158ea 100644 --- a/src/common/server.ts +++ b/src/common/server.ts @@ -38,7 +38,7 @@ import { import { updateServerKind, updateStatus } from "./status"; import { getProjectRoot } from "./utilities"; import { isVirtualWorkspace } from "./vscodeapi"; -import { spawn } from "child_process"; +import { execFile } from "child_process"; import which = require("which"); export type IInitializationOptions = { @@ -49,32 +49,15 @@ export type IInitializationOptions = { /** * Function to execute a command and return the stdout. */ -function executeCommand(cmd: string, args: string[] = []): Promise { +function executeFile(file: string, args: string[] = []): Promise { return new Promise((resolve, reject) => { - const child = spawn(cmd, args); - - let stdout = ""; - let stderr = ""; - - child.stdout.on("data", (data) => { - stdout += data.toString(); - }); - - child.stderr.on("data", (data) => { - stderr += data.toString(); - }); - - child.on("close", (code) => { - if (code !== 0) { - reject(new Error(stderr)); + execFile(file, args, (error, stdout, stderr) => { + if (error) { + reject(new Error(stderr || error.message)); } else { resolve(stdout); } }); - - child.on("error", (error) => { - reject(error); - }); }); } @@ -82,7 +65,7 @@ function executeCommand(cmd: string, args: string[] = []): Promise { * Get the version of the Ruff executable at the given path. */ async function getRuffVersion(executable: string): Promise { - const stdout = await executeCommand(executable, ["--version"]); + const stdout = await executeFile(executable, ["--version"]); const version = stdout.trim().split(" ")[1]; const [major, minor, patch] = version.split(".").map((x) => parseInt(x, 10)); return { major, minor, patch }; @@ -131,7 +114,7 @@ async function findRuffBinaryPath( // Otherwise, we'll call a Python script that tries to locate a binary. let ruffBinaryPath: string | undefined; try { - const stdout = await executeCommand(settings.interpreter[0], [FIND_RUFF_BINARY_SCRIPT_PATH]); + const stdout = await executeFile(settings.interpreter[0], [FIND_RUFF_BINARY_SCRIPT_PATH]); ruffBinaryPath = stdout.trim(); } catch (err) { await vscode.window