forked from google/zx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.test.js
385 lines (332 loc) · 11.2 KB
/
cli.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Copyright 2022 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 assert from 'node:assert'
import { test, describe, before, after } from 'node:test'
import { fileURLToPath } from 'node:url'
import net from 'node:net'
import getPort from 'get-port'
import { $, path, tmpfile, tmpdir, fs } from '../build/index.js'
import { isMain, normalizeExt, transformMarkdown } 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
const getServer = (resp = [], log = console.log) => {
const server = net.createServer()
server.on('connection', (conn) => {
conn.on('data', (d) => {
conn.write(resp.shift() || 'pong')
})
})
server.stop = () => new Promise((resolve) => server.close(() => resolve()))
server.start = (port) =>
new Promise((resolve) => server.listen(port, () => resolve(server)))
return server
}
describe('cli', () => {
// Helps to detect unresolved ProcessPromise.
before(() => {
const spawned = []
$.spawn = (...args) => {
const proc = spawn(...args)
const done = () => (proc._done = true)
spawned.push(proc)
return proc.once('close', done).once('error', done)
}
process.on('exit', () => {
if (spawned.some((p) => p._done !== true)) {
console.error('Error: ProcessPromise never resolved.')
process.exitCode = 1
}
})
})
after(() => ($.spawn = spawn))
test('promise resolved', async () => {
await $`echo`
})
test('prints version', async () => {
assert.match((await $`node build/cli.js -v`).toString(), /\d+.\d+.\d+/)
})
test('prints help', async () => {
const p = $`node build/cli.js -h`
p.stdin.end()
const help = await p
assert.match(help.stdout, /zx/)
})
test('zx prints usage if no param passed', async () => {
const p = $`node build/cli.js`
p.stdin.end()
try {
await p
assert.fail('must throw')
} catch (out) {
assert.match(out.stdout, /A tool for writing better scripts/)
assert.equal(out.exitCode, 1)
}
})
test('starts repl with --repl', async () => {
const p = $`node build/cli.js --repl`
p.stdin.write('await $`echo f"o"o`\n')
p.stdin.write('"b"+"ar"\n')
p.stdin.end()
const out = await p
assert.match(out.stdout, /foo/)
assert.match(out.stdout, /bar/)
})
test('starts repl with verbosity off', async () => {
const p = $`node build/cli.js --repl`
p.stdin.write('"verbose" + " is " + $.verbose\n')
p.stdin.end()
const out = await p
assert.match(out.stdout, /verbose is false/)
})
test('supports `--quiet` flag', async () => {
const p = await $`node build/cli.js --quiet test/fixtures/markdown.md`
assert.ok(!p.stderr.includes('ignore'), 'ignore was printed')
assert.ok(!p.stderr.includes('hello'), 'no hello')
assert.ok(p.stdout.includes('world'), 'no world')
})
test('supports `--shell` flag ', async () => {
const shell = $.shell
const p =
await $`node build/cli.js --verbose --shell=${shell} <<< '$\`echo \${$.shell}\`'`
assert.ok(p.stderr.includes(shell))
})
test('supports `--prefix` flag ', async () => {
const prefix = 'set -e;'
const p =
await $`node build/cli.js --verbose --prefix=${prefix} <<< '$\`echo \${$.prefix}\`'`
assert.ok(p.stderr.includes(prefix))
})
test('supports `--postfix` flag ', async () => {
const postfix = '; exit 0'
const p =
await $`node build/cli.js --verbose --postfix=${postfix} <<< '$\`echo \${$.postfix}\`'`
assert.ok(p.stderr.includes(postfix))
})
test('supports `--cwd` option ', async () => {
const cwd = path.resolve(fileURLToPath(import.meta.url), '../../temp')
fs.mkdirSync(cwd, { recursive: true })
const p =
await $`node build/cli.js --verbose --cwd=${cwd} <<< '$\`echo \${$.cwd}\`'`
assert.ok(p.stderr.endsWith(cwd + '\n'))
})
test('supports `--env` option', async () => {
const env = tmpfile(
'.env',
`FOO=BAR
BAR=FOO+`
)
const file = `
console.log((await $\`echo $FOO\`).stdout);
console.log((await $\`echo $BAR\`).stdout)
`
const out = await $`node build/cli.js --env=${env} <<< ${file}`
fs.remove(env)
assert.equal(out.stdout, 'BAR\n\nFOO+\n\n')
})
test('supports `--env` and `--cwd` options with file', async () => {
const env = tmpfile(
'.env',
`FOO=BAR
BAR=FOO+`
)
const dir = tmpdir()
const file = `
console.log((await $\`echo $FOO\`).stdout);
console.log((await $\`echo $BAR\`).stdout)
`
const out =
await $`node build/cli.js --cwd=${dir} --env=${env} <<< ${file}`
fs.remove(env)
fs.remove(dir)
assert.equal(out.stdout, 'BAR\n\nFOO+\n\n')
})
test('supports handling errors with the `--env` option', async () => {
const file = `
console.log((await $\`echo $FOO\`).stdout);
console.log((await $\`echo $BAR\`).stdout)
`
try {
await $`node build/cli.js --env=./env <<< ${file}`
fs.remove(env)
assert.throw()
} catch (e) {
assert.equal(e.exitCode, 1)
}
})
test('scripts from https 200', async () => {
const resp = await fs.readFile(path.resolve('test/fixtures/echo.http'))
const port = await getPort()
const server = await getServer([resp]).start(port)
const out =
await $`node build/cli.js --verbose http://127.0.0.1:${port}/script.mjs`
assert.match(out.stderr, /test/)
await server.stop()
})
test('scripts from https 500', async () => {
const port = await getPort()
const server = await getServer(['HTTP/1.1 500\n\n']).listen(port)
const out = await $`node build/cli.js http://127.0.0.1:${port}`.nothrow()
assert.match(out.stderr, /Error: Can't get/)
await server.stop()
})
test('scripts (md) from https', async () => {
const resp = await fs.readFile(path.resolve('test/fixtures/md.http'))
const port = await getPort()
const server = await getServer([resp]).start(port)
const out =
await $`node build/cli.js --verbose http://127.0.0.1:${port}/script.md`
assert.match(out.stderr, /md/)
await server.stop()
})
test('scripts with no extension', async () => {
await $`node build/cli.js test/fixtures/no-extension`
assert.ok(
/Test file to verify no-extension didn't overwrite similarly name .mjs file./.test(
(await fs.readFile('test/fixtures/no-extension.mjs')).toString()
)
)
})
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)'`
assert.match(out.stdout, /zx/)
})
test('require() is working in ESM', async () => {
await $`node build/cli.js test/fixtures/require.mjs`
})
test('__filename & __dirname are defined', async () => {
await $`node build/cli.js test/fixtures/filename-dirname.mjs`
})
test('markdown scripts are working', async () => {
await $`node build/cli.js test/fixtures/markdown.md`
})
test('markdown scripts are working for CRLF', async () => {
const p = await $`node build/cli.js test/fixtures/markdown-crlf.md`
assert.ok(p.stdout.includes('Hello, world!'))
})
test('exceptions are caught', async () => {
const out1 = await $`node build/cli.js <<<${'await $`wtf`'}`.nothrow()
const out2 = await $`node build/cli.js <<<'throw 42'`.nothrow()
assert.match(out1.stderr, /Error:/)
assert.match(out2.stderr, /42/)
})
test('eval works', async () => {
assert.equal((await $`node build/cli.js --eval 'echo(42)'`).stdout, '42\n')
assert.equal((await $`node build/cli.js -e='echo(69)'`).stdout, '69\n')
})
test('eval works with stdin', async () => {
const p = $`(printf foo; sleep 0.1; printf bar) | node build/cli.js --eval 'echo(await stdin())'`
assert.equal((await p).stdout, 'foobar\n')
})
test('executes a script from $PATH', async () => {
const isWindows = process.platform === 'win32'
const oldPath = process.env.PATH
const toPOSIXPath = (_path) => _path.split(path.sep).join(path.posix.sep)
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.')`
const scriptName = 'script-from-path'
const scriptFile = tmpfile(scriptName, scriptCode, 0o744)
const scriptDir = path.dirname(scriptFile)
const envPathSeparator = isWindows ? ';' : ':'
process.env.PATH += envPathSeparator + scriptDir
try {
await $`chmod +x ${zxLocation}`
await $`${scriptName}`
} finally {
process.env.PATH = oldPath
await fs.rm(scriptFile)
}
})
test('argv works with zx and node', async () => {
assert.equal(
(await $`node build/cli.js test/fixtures/argv.mjs foo`).toString(),
`global {"_":["foo"]}\nimported {"_":["foo"]}\n`
)
assert.equal(
(await $`node test/fixtures/argv.mjs bar`).toString(),
`global {"_":["bar"]}\nimported {"_":["bar"]}\n`
)
assert.equal(
(
await $`node build/cli.js --eval 'console.log(argv._.join(''))' baz`
).toString(),
`baz\n`
)
})
test('exit code can be set', async () => {
const p = await $`node build/cli.js test/fixtures/exit-code.mjs`.nothrow()
assert.equal(p.exitCode, 42)
})
describe('internals', () => {
test('isMain() checks process entry point', () => {
assert.equal(isMain(import.meta.url, __filename), true)
assert.equal(
isMain(import.meta.url.replace('.js', '.cjs'), __filename),
true
)
try {
assert.equal(
isMain(
'file:///root/zx/test/cli.test.js',
'/root/zx/test/all.test.js'
),
true
)
assert.throw()
} catch (e) {
assert.ok(['EACCES', 'ENOENT'].includes(e.code))
}
})
test('transformMarkdown()', () => {
// prettier-ignore
assert.equal(transformMarkdown(`
# Title
~~~js
await $\`echo "js"\`
~~~
typescript code block
~~~~~ts
await $\`echo "ts"\`
~~~~~
~~~
unknown code block
~~~
`), `//
// # Title
//
await $\`echo "js"\`
//
// typescript code block
await $\`echo "ts"\`
//
// unknown code block
//
// `)
})
test('normalizeExt()', () => {
assert.equal(normalizeExt('.ts'), '.ts')
assert.equal(normalizeExt('ts'), '.ts')
assert.equal(normalizeExt('.'), '.')
assert.equal(normalizeExt(), undefined)
})
})
})