All files / infrastructure/scripts/src/shared/adapters exec.ts

100% Statements 12/12
100% Branches 2/2
100% Functions 4/4
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45        7x     7x 3x                         7x 1x           1x       7x 2x     7x 25x 5x       20x    
import { execFileSync, spawnSync } from "node:child_process";
import { ExpectedError } from "../errors.ts";
 
// The 1 MiB default throws ENOBUFS on a large `git diff`.
const MAX_BUFFER_BYTES = 64 * 1024 * 1024;
 
/** Piping both streams keeps child errors and prompts inside this CLI's output handling. */
export const run = (command: string, args: string[]): string =>
    execFileSync(command, args, {
        encoding: "utf8",
        stdio: ["ignore", "pipe", "pipe"],
        maxBuffer: MAX_BUFFER_BYTES,
    }).trim();
 
export interface Captured {
    status: number | null;
    stdout: string;
    stderr: string;
}
 
/** For a child whose non-zero exit is an answer to report, not an error to throw. */
export const capture = (command: string, args: string[]): Captured => {
    const { status, stdout, stderr } = spawnSync(command, args, {
        encoding: "utf8",
        stdio: ["ignore", "pipe", "pipe"],
        maxBuffer: MAX_BUFFER_BYTES,
    });
 
    return { status, stdout, stderr };
};
 
/** A `null` status means a signal ended the child — Ctrl+C out of a dev server, not a failure. */
export const inherit = (command: string, args: string[]): number | null =>
    spawnSync(command, args, { stdio: "inherit" }).status;
 
/** A value starting with `-` is read as a flag, not a value — the injection shape SonarCloud flags. */
export const assertNotFlagLike = (value: string, field: string): string => {
    if (value.startsWith("-")) {
        throw new ExpectedError(
            `${field} can't start with "-" — it would be read as a flag, not a value: "${value}"`,
        );
    }
    return value;
};