feat: log executed command

Signed-off-by: Alfi Maulana <alfi.maulana.f@gmail.com>
This commit is contained in:
Alfi Maulana 2024-11-23 14:02:18 +07:00
parent c7ba931617
commit 7ad4029dc8
No known key found for this signature in database
GPG Key ID: 2242A64C2A8DF5A4
3 changed files with 31 additions and 1 deletions

11
dist/action.mjs generated vendored
View File

@ -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.
@ -62,6 +72,7 @@ function logError(err) {
*/
async function exec(command, args) {
return new Promise((resolve, reject) => {
logCommand(command, ...args);
const proc = spawn(command, args, {
stdio: ["ignore", "inherit", "inherit"],
});

View File

@ -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");
});
});

View File

@ -1,3 +1,4 @@
import { logCommand } from "gha-utils";
import { spawn } from "node:child_process";
/**
@ -11,6 +12,7 @@ import { spawn } from "node:child_process";
*/
export async function exec(command: string, args: string[]): Promise<void> {
return new Promise<void>((resolve, reject) => {
logCommand(command, ...args);
const proc = spawn(command, args, {
stdio: ["ignore", "inherit", "inherit"],
});