Commit a1a5ca7

Anton Medvedev <anton@medv.io>
2022-06-21 01:03:18
Fix argv initialization
1 parent a125bb2
Changed files (4)
src/cli.ts
@@ -20,6 +20,7 @@ import { tmpdir } from 'node:os'
 import { basename, dirname, extname, join, resolve } from 'node:path'
 import url from 'node:url'
 import './globals.js'
+import { updateArgv } from './goods.js'
 import { $, argv, chalk, fetch, ProcessOutput } from './index.js'
 import { startRepl } from './repl.js'
 import { randomId } from './util.js'
@@ -74,6 +75,7 @@ await (async function main() {
     } else {
       filepath = resolve(firstArg)
     }
+    updateArgv({ sliceAt: 3 })
     await importPath(filepath)
   }
   return (process.exitCode = 0)
src/goods.ts
@@ -26,7 +26,11 @@ export { default as YAML } from 'yaml'
 export { default as path } from 'node:path'
 export { default as os } from 'node:os'
 
-export const argv = minimist(process.argv.slice(2))
+export let argv = minimist(process.argv.slice(2))
+export function updateArgv(params: { sliceAt: number }) {
+  argv = minimist(process.argv.slice(params.sliceAt))
+  global.argv = argv
+}
 
 export const globby = Object.assign(function globby(
   patterns: string | readonly string[],
test/fixtures/argv.mjs
@@ -0,0 +1,20 @@
+#!/usr/bin/env zx
+
+// Copyright 2021 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import 'zx/globals'
+import { argv as importedArgv } from 'zx'
+console.log('global', JSON.stringify(argv))
+console.log('imported', JSON.stringify(importedArgv))
test/cli.test.js
@@ -169,4 +169,19 @@ test('executes a script from $PATH', async () => {
   }
 })
 
+test('argv works with zx and node', async () => {
+  assert.is(
+    (await $`node build/cli.js test/fixtures/argv.mjs foo`).toString(),
+    `global {"_":["foo"]}\nimported {"_":["foo"]}\n`
+  )
+  assert.is(
+    (await $`node test/fixtures/argv.mjs bar`).toString(),
+    `global {"_":["bar"]}\nimported {"_":["bar"]}\n`
+  )
+  assert.is(
+    (await $`node build/cli.js --eval 'console.log(argv._)' baz`).toString(),
+    `[ 'baz' ]\n`
+  )
+})
+
 test.run()