Commit aef8209

Will Clardy <will@quexxon.net>
2023-06-12 17:42:20
Enhance cd to accept ProcessOutput (#642)
* Enhance cd to accept ProcessOutput Satisfies #641 * Wrap cd test in within to avoid interference
1 parent d9f8a75
Changed files (3)
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()
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(() => {
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)