Commit 081b9f0

Anton Medvedev <anton@medv.io>
2022-06-05 16:14:11
Fix --eval for line with semicolons
1 parent 780c7e2
Changed files (2)
src/cli.ts
@@ -92,8 +92,15 @@ await (async function main() {
 })
 
 function addLogOnLastLine(script: string) {
-  let lines = script.trim().split('\n')
-  return lines.slice(0, -1).join('\n') + '\n' + `console.log(${lines.at(-1)})`
+  // We don't want to bring a JS parser as a dependency of zx,
+  // so the next code should work for most of the cases.
+  const lines = script.trim().split('\n')
+  let out = lines.slice(0, -1).join('\n') + '\n'
+  const lastLine = ';' + lines.at(-1)
+  const statements = lastLine.split(';')
+  out += statements.slice(0, -1).join(';') + ';'
+  out += `console.log(${statements.at(-1)})`
+  return out
 }
 
 async function runScript(script: string) {
test/cli.test.js
@@ -131,9 +131,19 @@ test('eval works with stdin', async () => {
   assert.is(stdout, 'Hello world\n')
 })
 
-test('--eval works with async stdin', async () => {
+test('eval works with async stdin', async () => {
   let p = $`(printf foo; sleep 0.1; printf bar) | FX_ASYNC_STDIN=true node build/cli.js --eval 'await stdin'`
   assert.is((await p).stdout, 'foobar\n')
 })
 
+test('eval works with newlines', async () => {
+  let p = $`node build/cli.js -e 'console.log(1)\nawait 2'`
+  assert.is((await p).stdout, '1\n2\n')
+})
+
+test('eval works with semicolon', async () => {
+  let p = $`node build/cli.js -e 'console.log(1); await 2'`
+  assert.is((await p).stdout, '1\n2\n')
+})
+
 test.run()