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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490// 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 assert from 'node:assert'
import { test, describe, after } from 'node:test'
import { Duplex } from 'node:stream'
import { $, chalk, fs, path, dotenv } from '../src/index.ts'
import {
echo,
sleep,
argv,
parseArgv,
updateArgv,
stdin,
spinner,
fetch,
retry,
question,
expBackoff,
tempfile,
tempdir,
tmpdir,
tmpfile,
versions,
} from '../src/goods.ts'
import { Writable } from 'node:stream'
import process from 'node:process'
const __dirname = new URL('.', import.meta.url).pathname
const root = path.resolve(__dirname, '..')
describe('goods', () => {
function zx(script) {
return $`node build/cli.js --eval ${script}`.nothrow().timeout('5s')
}
describe('question()', async () => {
test('works', async () => {
let contents = ''
class Input extends Duplex {
constructor() {
super()
}
_read() {}
_write(chunk, encoding, callback) {
this.push(chunk)
callback()
}
_final() {
this.push(null)
}
}
const input = new Input() as any
const output = new Writable({
write: function (chunk, encoding, next) {
contents += chunk.toString()
next()
},
}) as NodeJS.WriteStream
setTimeout(() => {
input.write('foo\n')
input.end()
}, 10)
const result = await question('foo or bar? ', {
choices: ['foo', 'bar'],
input,
output,
})
assert.equal(result, 'foo')
assert(contents.includes('foo or bar? '))
})
test('integration', async () => {
const p = $`node build/cli.js --eval "
let answer = await question('foo or bar? ', { choices: ['foo', 'bar'] })
echo('Answer is', answer)
"`
p.stdin.write('foo\n')
p.stdin.end()
assert.match((await p).stdout, /Answer is foo/)
})
})
test('echo() works', async () => {
const log = console.log
let stdout = ''
console.log = (...args) => {
stdout += args.join(' ')
}
echo(chalk.cyan('foo'), chalk.green('bar'), chalk.bold('baz'))
echo`${chalk.cyan('foo')} ${chalk.green('bar')} ${chalk.bold('baz')}`
echo(
await $`echo ${chalk.cyan('foo')}`,
await $`echo ${chalk.green('bar')}`,
await $`echo ${chalk.bold('baz')}`
)
console.log = log
assert.match(stdout, /foo/)
})
test('sleep() works', async () => {
const now = Date.now()
await sleep(100)
assert.ok(Date.now() >= now + 99)
})
describe('retry()', () => {
test('works', async () => {
let count = 0
const result = await retry(5, () => {
count++
if (count < 5) throw new Error('fail')
return 'success'
})
assert.equal(result, 'success')
assert.equal(count, 5)
})
test('works with custom delay and limit', async () => {
const now = Date.now()
let count = 0
try {
await retry(3, '2ms', () => {
count++
throw new Error('fail')
})
} catch (e) {
assert.match(e.message, /fail/)
assert.ok(Date.now() >= now + 4)
assert.equal(count, 3)
}
})
test('throws undefined on count misconfiguration', async () => {
try {
await retry(0, () => 'ok')
} catch (e) {
assert.equal(e, undefined)
}
})
test('throws err on empty callback', async () => {
try {
// @ts-ignore
await retry(5)
} catch (e) {
assert.match(e.message, /Callback is required for retry/)
}
})
test('supports expBackoff', async () => {
const result = await retry(5, expBackoff('10ms'), () => {
if (Math.random() < 0.1) throw new Error('fail')
return 'success'
})
assert.equal(result, 'success')
})
test('integration', async () => {
const now = Date.now()
const p = await zx(`
try {
await retry(5, '50ms', () => $\`exit 123\`)
} catch (e) {
echo('exitCode:', e.exitCode)
}
await retry(5, () => $\`exit 0\`)
echo('success')
`)
assert.ok(p.toString().includes('exitCode: 123'))
assert.ok(p.toString().includes('success'))
assert.ok(Date.now() >= now + 50 * (5 - 1))
})
test('integration with expBackoff', async () => {
const now = Date.now()
const p = await zx(`
try {
await retry(5, expBackoff('60s', 0), () => $\`exit 123\`)
} catch (e) {
echo('exitCode:', e.exitCode)
}
echo('success')
`)
assert.ok(p.toString().includes('exitCode: 123'))
assert.ok(p.toString().includes('success'))
assert.ok(Date.now() >= now + 2 + 4 + 8 + 16 + 32)
})
})
test('expBackoff()', async () => {
const g = expBackoff('10s', '100ms')
const [a, b, c] = [
g.next().value,
g.next().value,
g.next().value,
] as number[]
assert.equal(a, 100)
assert.equal(b, 200)
assert.equal(c, 400)
})
describe('spinner()', () => {
test('works', async () => {
let contents = ''
const { CI } = process.env
const output = new Writable({
write: function (chunk, encoding, next) {
contents += chunk.toString()
next()
},
})
delete process.env.CI
$.log.output = output as NodeJS.WriteStream
const p = spinner(() => sleep(100))
delete $.log.output
process.env.CI = CI
await p
assert(contents.includes('โ '))
})
describe('integration', () => {
test('works', async () => {
const out = await zx(
`
process.env.CI = ''
echo(await spinner(async () => {
await sleep(100)
await $\`echo hidden\`
return $\`echo result\`
}))
`
)
assert(out.stdout.includes('result'))
assert(out.stderr.includes('โ '))
assert(!out.stderr.includes('result'))
assert(!out.stderr.includes('hidden'))
})
test('with title', async () => {
const out = await zx(
`
process.env.CI = ''
await spinner('processing', () => sleep(100))
`
)
assert.match(out.stderr, /processing/)
})
test('disabled in CI', async () => {
const out = await zx(
`
process.env.CI = 'true'
await spinner('processing', () => sleep(100))
`
)
assert.doesNotMatch(out.stderr, /processing/)
})
test('stops on throw', async () => {
const out = await zx(`
await spinner('processing', () => $\`wtf-cmd\`)
`)
assert.match(out.stderr, /Error:/)
assert(out.exitCode !== 0)
})
})
})
describe('args', () => {
test('parseArgv() works', () => {
assert.deepEqual(
parseArgv(
// prettier-ignore
[
'--foo-bar', 'baz',
'-a', '5',
'-a', '42',
'--aaa', 'AAA',
'--force',
'./some.file',
'--b1', 'true',
'--b2', 'false',
'--b3',
'--b4', 'false',
'--b5', 'true',
'--b6', 'str'
],
{
boolean: ['force', 'b3', 'b4', 'b5', 'b6'],
camelCase: true,
parseBoolean: true,
alias: { a: 'aaa' },
},
{
def: 'def',
}
),
{
a: [5, 42, 'AAA'],
aaa: [5, 42, 'AAA'],
fooBar: 'baz',
force: true,
_: ['./some.file', 'str'],
b1: true,
b2: false,
b3: true,
b4: false,
b5: true,
b6: true,
def: 'def',
}
)
})
test('updateArgv() works', () => {
updateArgv(['--foo', 'bar'])
assert.deepEqual(argv, {
_: [],
foo: 'bar',
})
})
})
test('stdin()', async () => {
const stream = fs.createReadStream(path.resolve(root, 'package.json'))
const input = await stdin(stream)
assert.match(input, /"name": "zx"/)
})
test('fetch()', async () => {
const req1 = fetch('https://example.com/')
const req2 = fetch('https://example.com/')
const req3 = fetch('https://example.com/', { method: 'OPTIONS' })
const p1 = (await req1.pipe`cat`).stdout
const p2 = (await req2.pipe($`cat`)).stdout
const p3 = (await req3.pipe`cat`).stdout
assert.equal((await req1).status, 200)
assert.equal((await req2).status, 200)
assert.equal((await req3).status, 405)
assert(p1.includes('Example Domain'))
assert(p2.includes('Example Domain'))
assert(p3.includes('Example Domain'))
})
describe('dotenv', () => {
test('parse()', () => {
assert.deepEqual(dotenv.parse(''), {})
assert.deepEqual(
dotenv.parse('ENV=v1\nENV2=v2\n\n\n ENV3 = v3 \nexport ENV4=v4'),
{
ENV: 'v1',
ENV2: 'v2',
ENV3: 'v3',
ENV4: 'v4',
}
)
const multiline = `SIMPLE=xyz123
# comment ###
NON_INTERPOLATED='raw text without variable interpolation'
MULTILINE = """
long text here, # not-comment
e.g. a private SSH key
"""
ENV=v1\nENV2=v2\n\n\n\t\t ENV3 = v3 \n export ENV4=v4
ENV5=v5 # comment
`
assert.deepEqual(dotenv.parse(multiline), {
SIMPLE: 'xyz123',
NON_INTERPOLATED: 'raw text without variable interpolation',
MULTILINE: 'long text here, # not-comment\ne.g. a private SSH key',
ENV: 'v1',
ENV2: 'v2',
ENV3: 'v3',
ENV4: 'v4',
ENV5: 'v5',
})
})
describe('load()', () => {
const file1 = tempfile('.env.1', 'ENV1=value1\nENV2=value2')
const file2 = tempfile('.env.2', 'ENV2=value222\nENV3=value3')
after(() => Promise.all([fs.remove(file1), fs.remove(file2)]))
test('loads env from files', () => {
const env = dotenv.load(file1, file2)
assert.equal(env.ENV1, 'value1')
assert.equal(env.ENV2, 'value2')
assert.equal(env.ENV3, 'value3')
})
test('throws error on ENOENT', () => {
try {
dotenv.load('./.env')
throw new Error('unreachable')
} catch (e) {
assert.equal(e.code, 'ENOENT')
assert.equal(e.errno, -2)
}
})
})
describe('loadSafe()', () => {
const file1 = tempfile('.env.1', 'ENV1=value1\nENV2=value2')
const file2 = '.env.notexists'
after(() => fs.remove(file1))
test('loads env from files', () => {
const env = dotenv.loadSafe(file1, file2)
assert.equal(env.ENV1, 'value1')
assert.equal(env.ENV2, 'value2')
})
})
describe('config()', () => {
test('updates process.env', () => {
const file1 = tempfile('.env.1', 'ENV1=value1')
assert.equal(process.env.ENV1, undefined)
dotenv.config(file1)
assert.equal(process.env.ENV1, 'value1')
delete process.env.ENV1
})
})
})
describe('temp*', () => {
test('tempdir() creates temporary folders', () => {
assert.equal(tmpdir, tempdir)
assert.match(tempdir(), /\/zx-/)
assert.match(tempdir('foo'), /\/foo$/)
})
test('tempfile() creates temporary files', () => {
assert.equal(tmpfile, tempfile)
assert.match(tempfile(), /\/zx-.+/)
assert.match(tempfile('foo.txt'), /\/zx-.+\/foo\.txt$/)
const tf = tempfile('bar.txt', 'bar')
assert.match(tf, /\/zx-.+\/bar\.txt$/)
assert.equal(fs.readFileSync(tf, 'utf-8'), 'bar')
})
})
describe('versions', () => {
test('exports deps versions', () => {
assert.deepEqual(
Object.keys(versions).sort(),
[
'chalk',
'depseek',
'dotenv',
'fetch',
'fs',
'glob',
'minimist',
'ps',
'which',
'yaml',
'zx',
].sort()
)
})
})
})