From a93af4bd1e2dab8211d037cb561a6173366f97d8 Mon Sep 17 00:00:00 2001 From: Alfi Maulana Date: Sun, 24 Nov 2024 22:34:31 +0700 Subject: [PATCH] feat: log executed command (#524) * feat: log executed command Signed-off-by: Alfi Maulana * feat: log command based on spawned process arguments Signed-off-by: Alfi Maulana --------- Signed-off-by: Alfi Maulana --- dist/action.mjs | 11 +++++++++++ src/exec.test.ts | 19 ++++++++++++++++++- src/exec.ts | 2 ++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/dist/action.mjs b/dist/action.mjs index 5b8ed0e..f639502 100644 --- a/dist/action.mjs +++ b/dist/action.mjs @@ -50,6 +50,16 @@ function logError(err) { const message = err instanceof Error ? err.message : String(err); process.stdout.write(`::error::${message}${os.EOL}`); } +/** + * Logs a command along with its arguments in GitHub Actions. + * + * @param command - The command to log. + * @param args - The arguments of the command. + */ +function logCommand(command, ...args) { + const message = [command, ...args].join(" "); + process.stdout.write(`[command]${message}${os.EOL}`); +} /** * Executes a command with the given arguments. @@ -65,6 +75,7 @@ async function exec(command, args) { const proc = spawn(command, args, { stdio: ["ignore", "inherit", "inherit"], }); + logCommand(proc.spawnfile, ...proc.spawnargs.splice(1)); proc.on("error", reject); proc.on("close", (code) => { if (code === 0) { diff --git a/src/exec.test.ts b/src/exec.test.ts index 0aca427..95ba57a 100644 --- a/src/exec.test.ts +++ b/src/exec.test.ts @@ -1,13 +1,30 @@ -import { exec } from "./exec.js"; +import { jest } from "@jest/globals"; describe("execute commands", () => { + const logCommand = jest.fn<(command: string, ...args: string[]) => void>(); + jest.unstable_mockModule("gha-utils", () => ({ logCommand })); + + beforeEach(() => { + logCommand.mockClear(); + }); + it("should successfully execute a command", async () => { + const { exec } = await import("./exec.js"); + await exec("node", ["--version"]); + + expect(logCommand).toHaveBeenCalledTimes(1); + expect(logCommand).toHaveBeenCalledWith("node", "--version"); }); it("should fail to execute a command", async () => { + const { exec } = await import("./exec.js"); + await expect(exec("node", ["--invalid"])).rejects.toThrow( "Command exited with status code 9", ); + + expect(logCommand).toHaveBeenCalledTimes(1); + expect(logCommand).toHaveBeenCalledWith("node", "--invalid"); }); }); diff --git a/src/exec.ts b/src/exec.ts index 4d5f222..2e3e00b 100644 --- a/src/exec.ts +++ b/src/exec.ts @@ -1,3 +1,4 @@ +import { logCommand } from "gha-utils"; import { spawn } from "node:child_process"; /** @@ -14,6 +15,7 @@ export async function exec(command: string, args: string[]): Promise { const proc = spawn(command, args, { stdio: ["ignore", "inherit", "inherit"], }); + logCommand(proc.spawnfile, ...proc.spawnargs.splice(1)); proc.on("error", reject); proc.on("close", (code) => { if (code === 0) {