From 7640372f896ba8e4bd901280bf3748198a1b5dc7 Mon Sep 17 00:00:00 2001 From: David Sherret Date: Sun, 28 Jan 2024 11:36:34 -0500 Subject: [PATCH] feat: error when providing an unexpected object that doesn't override `toString()` in a command expr (#231) --- mod.test.ts | 29 +++++++++++++++++++++++++++++ src/command.ts | 6 +++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/mod.test.ts b/mod.test.ts index ca4f063..7645916 100644 --- a/mod.test.ts +++ b/mod.test.ts @@ -169,6 +169,35 @@ Deno.test("should throw when exit code is non-zero", async () => { ); }); +Deno.test("throws when providing an object that doesn't override toString", async () => { + { + const obj1 = {}; + assertThrows( + () => $`echo ${obj1}`, + Error, + "Failed resolving expression in command. Provided object does not override `toString()`.", + ); + } + { + const obj2 = { + toString() { + return "1"; + }, + }; + const result = await $`echo ${obj2}`.text(); + assertEquals(result, "1"); + } + class Test { + toString() { + return 1; + } + } + { + const result = await $`echo ${new Test()}`.text(); + assertEquals(result, "1"); + } +}); + Deno.test("should change the cwd, but only in the shell", async () => { const output = await $`cd src ; deno eval 'console.log(Deno.cwd());'`.stdout("piped"); const standardizedOutput = output.stdout.trim().replace(/\\/g, "/"); diff --git a/src/command.ts b/src/command.ts index 3942100..0107673 100644 --- a/src/command.ts +++ b/src/command.ts @@ -1418,11 +1418,15 @@ function detectInputOrOutputRedirect(text: string) { function templateLiteralExprToString(expr: any, escape: ((arg: string) => string) | undefined): string { let result: string; - if (expr instanceof Array) { + if (typeof expr === "string") { + result = expr; + } else if (expr instanceof Array) { return expr.map((e) => templateLiteralExprToString(e, escape)).join(" "); } else if (expr instanceof CommandResult) { // remove last newline result = expr.stdout.replace(/\r?\n$/, ""); + } else if (typeof expr === "object" && expr.toString === Object.prototype.toString) { + throw new Error("Provided object does not override `toString()`."); } else { result = `${expr}`; }