Skip to content

Commit

Permalink
Fix runProcess to fully finish the process (#41)
Browse files Browse the repository at this point in the history
`exec` did not wait for the `git` process to finish, which caused issues
when using `git checkout` >1 time in a row. We should have been using
the `spawn` API instead.
  • Loading branch information
Eric-Arellano authored Jul 8, 2023
1 parent ef25425 commit ea42f38
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 14 deletions.
32 changes: 21 additions & 11 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-console */

import { exec, ExecOptions } from "child_process";
import { spawn, SpawnOptionsWithoutStdio } from "child_process";

import { Point } from "@influxdata/influxdb-client";

Expand All @@ -22,19 +22,29 @@ const createCountPoint = (

const runProcess = (
cmd: string,
options?: ExecOptions
args: string[],
options?: SpawnOptionsWithoutStdio
): Promise<[string, string]> =>
new Promise((resolve, reject) => {
exec(cmd, options, (error, stdout, stderr) => {
if (error) {
return reject(error);
}
if (stdout instanceof Buffer || stderr instanceof Buffer) {
return reject(
new Error("stdout or stderr is Buffer, which is not supported")
);
const child = spawn(cmd, args, options);

let output = "";
child.stdout.on("data", (data) => {
output += data;
});

let errorOutput = "";
child.stderr.on("data", (data) => {
errorOutput += data;
});

child.on("error", reject);
child.on("close", (code) => {
if (code === 0) {
resolve([output, errorOutput]);
} else {
reject(new Error(`Command exited with code ${code}: ${errorOutput}`));
}
return resolve([stdout, stderr]);
});
});

Expand Down
9 changes: 6 additions & 3 deletions tests/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,23 @@ import { runProcess } from "../src/utils";

test.describe("runProcess", () => {
test("captures stdout", async () => {
const [stdout, stderr] = await runProcess("echo 'hello world'");
const [stdout, stderr] = await runProcess("echo", ["hello world"]);
expect(stdout).toEqual("hello world\n");
expect(stderr).toEqual("");
});

test("captures stderr", async () => {
const [stdout, stderr] = await runProcess("echo 'hello world' 1>&2");
const [stdout, stderr] = await runProcess("node", [
"-e",
"console.error('hello world')",
]);
expect(stdout).toEqual("");
expect(stderr).toEqual("hello world\n");
});

test("errors on failures", async () => {
try {
await runProcess("fake-process");
await runProcess("fake-process", []);
} catch (error) {
expect(error).toBeTruthy();
}
Expand Down

0 comments on commit ea42f38

Please sign in to comment.