Skip to content

Commit

Permalink
feat(cli): allow to override default script extension
Browse files Browse the repository at this point in the history
closes google#929
  • Loading branch information
antongolub committed Nov 8, 2024
1 parent 3f164e0 commit 4174fd1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import { installDeps, parseDeps } from './deps.js'
import { randomId } from './util.js'
import { createRequire } from './vendor.js'

const EXT = '.mjs'

isMain() &&
main().catch((err) => {
if (err instanceof ProcessOutput) {
Expand Down Expand Up @@ -56,6 +58,7 @@ export function printUsage() {
--postfix=<command> postfix all commands
--cwd=<path> set current directory
--eval=<js>, -e evaluate script
--ext=<.mjs> eval extension
--install, -i install dependencies
--version, -v print current zx version
--help, -h print help
Expand All @@ -67,7 +70,7 @@ export function printUsage() {
}

export const argv = minimist(process.argv.slice(2), {
string: ['shell', 'prefix', 'postfix', 'eval', 'cwd'],
string: ['shell', 'prefix', 'postfix', 'eval', 'cwd', 'ext'],
boolean: [
'version',
'help',
Expand Down Expand Up @@ -102,21 +105,21 @@ export async function main() {
return
}
if (argv.eval) {
await runScript(argv.eval)
await runScript(argv.eval, argv.ext)
return
}
const firstArg = argv._[0]
updateArgv(argv._.slice(firstArg === undefined ? 0 : 1))
if (!firstArg || firstArg === '-') {
const success = await scriptFromStdin()
const success = await scriptFromStdin(argv.ext)
if (!success) {
printUsage()
process.exitCode = 1
}
return
}
if (/^https?:/.test(firstArg)) {
await scriptFromHttp(firstArg)
await scriptFromHttp(firstArg, argv.ext)
return
}
const filepath = firstArg.startsWith('file:///')
Expand All @@ -125,12 +128,12 @@ export async function main() {
await importPath(filepath)
}

export async function runScript(script: string) {
const filepath = path.join($.cwd ?? process.cwd(), `zx-${randomId()}.mjs`)
export async function runScript(script: string, ext = EXT) {
const filepath = path.join($.cwd ?? process.cwd(), `zx-${randomId()}${ext}`)
await writeAndImport(script, filepath)
}

export async function scriptFromStdin() {
export async function scriptFromStdin(ext?: string) {
let script = ''
if (!process.stdin.isTTY) {
process.stdin.setEncoding('utf8')
Expand All @@ -139,14 +142,14 @@ export async function scriptFromStdin() {
}

if (script.length > 0) {
await runScript(script)
await runScript(script, ext)
return true
}
}
return false
}

export async function scriptFromHttp(remote: string) {
export async function scriptFromHttp(remote: string, _ext = EXT) {
const res = await fetch(remote)
if (!res.ok) {
console.error(`Error: Can't get ${remote}`)
Expand All @@ -155,7 +158,7 @@ export async function scriptFromHttp(remote: string) {
const script = await res.text()
const pathname = new URL(remote).pathname
const name = path.basename(pathname)
const ext = path.extname(pathname) || '.mjs'
const ext = path.extname(pathname) || _ext
const cwd = $.cwd ?? process.cwd()
const filepath = path.join(cwd, `${name}-${randomId()}${ext}`)
await writeAndImport(script, filepath)
Expand Down
9 changes: 9 additions & 0 deletions test/cli.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ import { isMain } from '../build/cli.js'

const __filename = fileURLToPath(import.meta.url)
const spawn = $.spawn
const nodeMajor = +process.versions?.node?.split('.')[0]
const test22 = nodeMajor >= 22 ? test : test.skip

describe('cli', () => {
// Helps detect unresolved ProcessPromise.
before(() => {
Expand Down Expand Up @@ -144,6 +147,12 @@ describe('cli', () => {
)
})

test22('scripts from stdin with explicit extension', async () => {
const out =
await $`node --experimental-strip-types build/cli.js --ext='.ts' <<< 'const foo: string = "bar"; console.log(foo)'`
assert.match(out.stdout, /bar/)
})

test('require() is working from stdin', async () => {
const out =
await $`node build/cli.js <<< 'console.log(require("./package.json").name)'`
Expand Down

0 comments on commit 4174fd1

Please sign in to comment.