Skip to content

Commit

Permalink
feat: error when providing an unexpected object that doesn't override…
Browse files Browse the repository at this point in the history
… `toString()` in a command expr (#231)
  • Loading branch information
dsherret authored Jan 28, 2024
1 parent 4d39bf3 commit 7640372
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
29 changes: 29 additions & 0 deletions mod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, "/");
Expand Down
6 changes: 5 additions & 1 deletion src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
}
Expand Down

0 comments on commit 7640372

Please sign in to comment.