Skip to content

Commit

Permalink
feat: support providing an array of expressions as arguments (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
dsherret committed Oct 14, 2022
1 parent f6578a4 commit b25484f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ await $`echo 5`;
// expressions provided to the template literal are escaped if necessary
const dirName = "Dir with spaces";
await $`mkdir ${dirName}`; // executes as: mkdir 'Dir with spaces'
const dirNames = ["some_dir", "other dir"];
await $`mkdir ${dirNames}`; // executes as: mkdir some_dir 'other dir'

// get the stdout of a command (makes stdout "quiet")
const result = await $`echo 1`.text();
Expand Down
6 changes: 6 additions & 0 deletions mod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,12 @@ Deno.test("should handle interpolation", async () => {
assertEquals(output.stdout, "5\n");
});

Deno.test("should handle providing array of arguments", async () => {
const args = [1, "2", "test test"];
const text = await $`deno eval 'console.log(Deno.args)' ${args}`.text();
assertEquals(text, `[ "1", "2", "test test" ]`);
});

Deno.test("command builder should build", async () => {
const commandBuilder = new CommandBuilder()
.env("TEST", "123");
Expand Down
19 changes: 12 additions & 7 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,13 +419,7 @@ export function build$(options: Create$Options) {
result += strings[i];
}
if (exprs.length > i) {
const expr = exprs[i];
if (expr instanceof CommandResult) {
// remove last newline
result += escapeArg(expr.stdout.replace(/\r?\n$/, ""));
} else {
result += escapeArg(`${exprs[i]}`);
}
result += templateLiteralExprToString(exprs[i]);
}
}
return commandBuilder.command(result);
Expand All @@ -443,6 +437,17 @@ export function build$(options: Create$Options) {
return result;
}

function templateLiteralExprToString(expr: any): string {
if (expr instanceof Array) {
return expr.map(e => templateLiteralExprToString(e)).join(" ");
} else if (expr instanceof CommandResult) {
// remove last newline
return escapeArg(expr.stdout.replace(/\r?\n$/, ""));
} else {
return escapeArg(`${expr}`);
}
}

/**
* Default `$` where commands may be executed.
*/
Expand Down

0 comments on commit b25484f

Please sign in to comment.