Commit 9725997

Markos Konstantopoulos <markoskonstanto@hotmail.com>
2021-08-10 12:40:07
Run script from path (#173)
* * Add a test that runs a script from PATH. * Use path.resolve instead of join to run scripts from PATH on Windows. * Remove script extension in PATH test. Co-authored-by: Anton Medvedev <antonmedv@google.com>
1 parent 3f5d50a
Changed files (2)
test.mjs
@@ -13,6 +13,7 @@
 // limitations under the License.
 
 import {strict as assert, deepEqual} from 'assert'
+import path from 'path'
 
 { // Only stdout is used during command substitution
   let hello = await $`echo Error >&2; echo Hello`
@@ -151,4 +152,28 @@ import {strict as assert, deepEqual} from 'assert'
   console.log(chalk.black.bgYellowBright(` ${name} version is ${version} `))
 }
 
+{ // Executes a script from PATH.
+  const isWindows = process.platform === 'win32'
+  const oldPath = process.env.PATH
+
+  const envPathSeparator = isWindows ? ';' : ':'
+  process.env.PATH +=  envPathSeparator + path.resolve('/tmp/')
+
+  const toPOSIXPath = (_path) =>
+    _path.split(path.sep).join(path.posix.sep)
+
+  const zxPath = path.resolve('./zx.mjs')
+  const zxLocation = isWindows ? toPOSIXPath(zxPath) : zxPath
+  const scriptCode = `#!/usr/bin/env ${zxLocation}\nconsole.log('The script from path runs.')`
+
+  try {
+    await $`echo ${scriptCode}`
+      .pipe(fs.createWriteStream('/tmp/script-from-path', { mode: 0o744 }))
+    await $`script-from-path`
+  } finally {
+    process.env.PATH = oldPath
+    fs.rm('/tmp/script-from-path')
+  }
+}
+
 console.log(chalk.greenBright(' 🍺 Success!'))
zx.mjs
@@ -42,7 +42,7 @@ try {
     } else if (firstArg.startsWith('file:///')) {
       filepath = url.fileURLToPath(firstArg)
     } else {
-      filepath = join(process.cwd(), firstArg)
+      filepath = resolve(firstArg)
     }
     await importPath(filepath)
   }