Commit c3fbe9a

Anton Medvedev <anton@medv.io>
2022-05-29 21:57:32
Move zx.mjs to cli.ts
1 parent 8c2aea8
zx.js → src/cli.ts
@@ -26,8 +26,9 @@ import {
   fetch,
   ProcessOutput,
   registerGlobals,
-} from './build/index.js'
-import { randomId } from './build/util.js'
+  chalk,
+} from './index.js'
+import { randomId } from './util.js'
 
 await (async function main() {
   registerGlobals()
@@ -39,11 +40,11 @@ await (async function main() {
     $.prefix = argv.prefix
   }
   if (argv.experimental) {
-    Object.assign(global, await import('./build/experimental.js'))
+    Object.assign(global, await import('./experimental.js'))
   }
   try {
     if (['--version', '-v', '-V'].includes(process.argv[2])) {
-      console.log(createRequire(import.meta.url)('./package.json').version)
+      console.log(createRequire(import.meta.url)('../package.json').version)
       return (process.exitCode = 0)
     }
     let firstArg = process.argv.slice(2).find((a) => !a.startsWith('--'))
@@ -77,6 +78,7 @@ await (async function main() {
       throw p
     }
   }
+  return (process.exitCode = 0)
 })()
 
 async function scriptFromStdin() {
@@ -97,7 +99,7 @@ async function scriptFromStdin() {
   return false
 }
 
-async function scriptFromHttp(remote) {
+async function scriptFromHttp(remote: string) {
   let res = await fetch(remote)
   if (!res.ok) {
     console.error(`Error: Can't get ${remote}`)
@@ -114,14 +116,18 @@ async function scriptFromHttp(remote) {
   )
 }
 
-async function writeAndImport(script, filepath, origin = filepath) {
-  await fs.writeFile(filepath, script)
+async function writeAndImport(
+  script: string | Buffer,
+  filepath: string,
+  origin = filepath
+) {
+  await fs.writeFile(filepath, script.toString())
   let wait = importPath(filepath, origin)
   await fs.rm(filepath)
   await wait
 }
 
-async function importPath(filepath, origin = filepath) {
+async function importPath(filepath: string, origin = filepath) {
   let ext = extname(filepath)
 
   if (ext === '') {
@@ -137,7 +143,7 @@ async function importPath(filepath, origin = filepath) {
   }
   if (ext === '.md') {
     return await writeAndImport(
-      transformMarkdown((await fs.readFile(filepath)).toString()),
+      transformMarkdown(await fs.readFile(filepath)),
       join(dirname(filepath), basename(filepath) + '.mjs'),
       origin
     )
@@ -146,10 +152,11 @@ async function importPath(filepath, origin = filepath) {
   let __dirname = dirname(__filename)
   let require = createRequire(origin)
   Object.assign(global, { __filename, __dirname, require })
-  await import(url.pathToFileURL(filepath))
+  await import(url.pathToFileURL(filepath).toString())
 }
 
-function transformMarkdown(source) {
+function transformMarkdown(buf: Buffer) {
+  let source = buf.toString()
   let output = []
   let state = 'root'
   let prevLineIsEmpty = true
test/zx.test.js → test/cli.test.js
@@ -14,17 +14,17 @@
 
 import { assert, testFactory } from './test-utils.js'
 
-const test = testFactory('zx', import.meta)
+const test = testFactory('cli', import.meta)
 
 test('supports `-v` flag / prints version', async () => {
-  let v = (await $`node zx.js -v`).toString().trim()
+  let v = (await $`node build/cli.js -v`).toString().trim()
   assert.equal(v, require('../package.json').version)
 })
 
 test('prints help', async () => {
   let help
   try {
-    await $`node zx.js`
+    await $`node build/cli.js`
   } catch (err) {
     help = err.toString().trim()
   }
@@ -32,45 +32,45 @@ test('prints help', async () => {
 })
 
 test('supports `--experimental` flag', async () => {
-  await $`echo 'echo("test")' | node zx.js --experimental`
+  await $`echo 'echo("test")' | node build/cli.js --experimental`
 })
 
 test('supports `--quiet` flag / Quiet mode is working', async () => {
-  let p = await $`node zx.js --quiet docs/markdown.md`
+  let p = await $`node build/cli.js --quiet docs/markdown.md`
   assert(!p.stdout.includes('whoami'))
 })
 
 test('supports `--shell` flag ', async () => {
   let shell = $.shell
-  let p = await $`node zx.js --shell=${shell} <<< '$\`echo \${$.shell}\`'`
+  let p = await $`node build/cli.js --shell=${shell} <<< '$\`echo \${$.shell}\`'`
   assert(p.stdout.includes(shell))
 })
 
 test('supports `--prefix` flag ', async () => {
   let prefix = 'set -e;'
-  let p = await $`node zx.js --prefix=${prefix} <<< '$\`echo \${$.prefix}\`'`
+  let p = await $`node build/cli.js --prefix=${prefix} <<< '$\`echo \${$.prefix}\`'`
   assert(p.stdout.includes(prefix))
 })
 
-test('Eval script from https ref', async () => {
+test('scripts from https', async () => {
   let script = path.resolve('test/fixtures/echo.http')
   let server = quiet($`while true; do cat ${script} | nc -l 8080; done`)
-  let p = await quiet($`node zx.js http://127.0.0.1:8080/echo.mjs`)
+  let p = await quiet($`node build/cli.js http://127.0.0.1:8080/echo.mjs`)
 
   assert(p.stdout.includes('test'))
   server.kill()
 
   let err
   try {
-    await quiet($`node zx.js http://127.0.0.1:8081/echo.mjs`)
+    await quiet($`node build/cli.js http://127.0.0.1:8081/echo.mjs`)
   } catch (e) {
     err = e
   }
   assert(err.stderr.includes('ECONNREFUSED'))
 })
 
-test('Scripts with no extension', async () => {
-  await $`node zx.js test/fixtures/no-extension`
+test('scripts with no extension', async () => {
+  await $`node build/cli.js test/fixtures/no-extension`
   assert.match(
     (await fs.readFile('test/fixtures/no-extension.mjs')).toString(),
     /Test file to verify no-extension didn't overwrite similarly name .mjs file./
@@ -78,9 +78,9 @@ test('Scripts with no extension', async () => {
 })
 
 test('The require() is working from stdin', async () => {
-  await $`node zx.js <<< 'require("./package.json").name'`
+  await $`node build/cli.js <<< 'require("./package.json").name'`
 })
 
 test('Markdown scripts are working', async () => {
-  await $`node zx.js docs/markdown.md`
+  await $`node build/cli.js docs/markdown.md`
 })
test/full.test.js
@@ -12,6 +12,6 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-import './zx.test.js'
+import './cli.test.js'
 import './index.test.js'
 import './experimental.test.js'
test/index.test.js
@@ -82,7 +82,7 @@ test('The toString() is called on arguments', async () => {
 
 test('Can use array as an argument', async () => {
   try {
-    let files = ['./zx.js', './test/index.test.js']
+    let files = ['./cli.ts', './test/index.test.js']
     await $`tar czf archive ${files}`
   } finally {
     await $`rm archive`
@@ -248,11 +248,12 @@ test('Executes a script from $PATH', async () => {
 
   const toPOSIXPath = (_path) => _path.split(path.sep).join(path.posix.sep)
 
-  const zxPath = path.resolve('./zx.js')
+  const zxPath = path.resolve('./build/cli.js')
   const zxLocation = isWindows ? toPOSIXPath(zxPath) : zxPath
   const scriptCode = `#!/usr/bin/env ${zxLocation}\nconsole.log('The script from path runs.')`
 
   try {
+    await $`chmod +x ${zxLocation}`
     await $`echo ${scriptCode}`.pipe(
       fs.createWriteStream('/tmp/script-from-path', { mode: 0o744 })
     )
package.json
@@ -9,12 +9,12 @@
     ".": "./build/index.js",
     "./globals": "./build/globals.js",
     "./experimental": "./build/experimental.js",
-    "./cli": "./zx.js",
+    "./cli": "./build/cli.js",
     "./core": "./build/core.js",
     "./package.json": "./package.json"
   },
   "bin": {
-    "zx": "zx.js"
+    "zx": "./build/cli.js"
   },
   "engines": {
     "node": ">= 16.0.0"
@@ -22,11 +22,8 @@
   "scripts": {
     "fmt": "prettier --write .",
     "build": "tsc",
-    "test": "tsc && npm run test:unit",
-    "test:unit": "node zx.js test/full.test.js",
-    "test:cov": "c8 --reporter=html npm run test:unit",
-    "test:zx": "npm run test zx",
-    "test:index": "npm run test index"
+    "test": "tsc && node build/cli.js test/full.test.js",
+    "coverage": "c8 --reporter=html npm run test:unit"
   },
   "dependencies": {
     "@types/fs-extra": "^9.0.13",