From aef8209b06b19a6ccf54ad175b59802920d5aee4 Mon Sep 17 00:00:00 2001 From: Will Clardy Date: Mon, 12 Jun 2023 11:42:20 -0400 Subject: [PATCH] Enhance cd to accept ProcessOutput (#642) * Enhance cd to accept ProcessOutput Satisfies #641 * Wrap cd test in within to avoid interference --- README.md | 7 +++++++ src/core.ts | 6 +++++- test/core.test.js | 8 ++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f69d6d932b..6fcf5ed6d5 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,13 @@ cd('/tmp') await $`pwd` // => /tmp ``` +Like `echo`, in addition to `string` arguments, `cd` accepts and trims +trailing newlines from `ProcessOutput` enabling common idioms like: + +```js +cd(await $`mktemp -d`) +``` + ### `fetch()` A wrapper around the [node-fetch](https://www.npmjs.com/package/node-fetch) diff --git a/src/core.ts b/src/core.ts index 8169b0830b..17a03e8508 100644 --- a/src/core.ts +++ b/src/core.ts @@ -441,7 +441,11 @@ function syncCwd() { if ($[processCwd] != process.cwd()) process.chdir($[processCwd]) } -export function cd(dir: string) { +export function cd(dir: string | ProcessOutput) { + if (dir instanceof ProcessOutput) { + dir = dir.toString().replace(/\n+$/, '') + } + $.log({ kind: 'cd', dir }) process.chdir(dir) $[processCwd] = process.cwd() diff --git a/test/core.test.js b/test/core.test.js index 587dd5979c..62787bc65c 100644 --- a/test/core.test.js +++ b/test/core.test.js @@ -233,6 +233,14 @@ test('cd() fails on entering not existing dir', async () => { assert.throws(() => cd('/tmp/abra-kadabra')) }) +test('cd() accepts ProcessOutput in addition to string', async () => { + within(async () => { + const tmpDir = await $`mktemp -d` + cd(tmpDir) + assert.match(process.cwd(), tmpDir.toString().trimEnd()) + }) +}) + test('kill() method works', async () => { let p = $`sleep 9999`.nothrow() setTimeout(() => {