Commit 5f54045

Anton Medvedev <anton@medv.io>
2022-01-16 20:48:53
Make cd() work with relative paths and process.cwd()
1 parent 76f1f4d
index.d.ts
@@ -27,7 +27,6 @@ interface $ {
 
   verbose: boolean
   shell: string
-  cwd: string
   prefix: string
   quote: (input: string) => string
 }
index.mjs
@@ -53,7 +53,7 @@ export function registerGlobals() {
 }
 
 export function $(pieces, ...args) {
-  let {verbose, cwd, shell, prefix} = $
+  let {verbose, shell, prefix} = $
   let __from = (new Error().stack.split(/^\s*at\s/m)[2]).trim()
 
   let cmd = pieces[0], i = 0
@@ -78,7 +78,7 @@ export function $(pieces, ...args) {
     }
 
     let child = spawn(prefix + cmd, {
-      cwd,
+      cwd: process.cwd(),
       shell: typeof shell === 'string' ? shell : true,
       stdio: [promise._inheritStdin ? 'inherit' : 'pipe', 'pipe', 'pipe'],
       windowsHide: true,
@@ -131,17 +131,10 @@ if (typeof argv.prefix === 'string') {
   $.prefix = argv.prefix
 }
 $.quote = quote
-$.cwd = undefined
 
 export function cd(path) {
   if ($.verbose) console.log('$', colorize(`cd ${path}`))
-  if (!fs.existsSync(path)) {
-    let __from = (new Error().stack.split(/^\s*at\s/m)[2]).trim()
-    console.error(`cd: ${path}: No such directory`)
-    console.error(`    at ${__from}`)
-    process.exit(1)
-  }
-  $.cwd = path
+  process.chdir(path)
 }
 
 export async function question(query, options) {
test.mjs
@@ -12,7 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-import {strict as assert, deepEqual} from 'assert'
+import {strict as assert} from 'assert'
 
 { // Only stdout is used during command substitution
   let hello = await $`echo Error >&2; echo Hello`
@@ -191,7 +191,7 @@ import {strict as assert, deepEqual} from 'assert'
     await $`script-from-path`
   } finally {
     process.env.PATH = oldPath
-    fs.rm('/tmp/script-from-path')
+    fs.rmSync('/tmp/script-from-path')
   }
 }
 
@@ -200,6 +200,19 @@ import {strict as assert, deepEqual} from 'assert'
   assert.match(stdout, /Hello from CommonJS/)
 }
 
+{ // cd() works with relative paths.
+  try {
+    fs.mkdirpSync('/tmp/zx-cd-test/one/two')
+    cd('/tmp/zx-cd-test/one/two')
+    cd('..')
+    cd('..')
+    let pwd = (await $`pwd`).stdout.trim()
+    assert.equal(path.basename(pwd), 'zx-cd-test')
+  } finally {
+    fs.rmSync('/tmp/zx-cd-test', {recursive: true})
+  }
+}
+
 { // require() is working in ESM
   const {name, version} = require('./package.json')
   assert(typeof name === 'string')