Commit f506036

Anton Golub <mailbox@antongolub.ru>
2022-03-18 16:52:30
refactor: simplify echo helper, add tests for experimental features (#353)
* refactor: simplify echo helper, add tests for experimental features * style: linting * revert: replace arr.proto.at with legacy index * chore: rm useless import
1 parent 2a38238
src/experimental.mjs
@@ -37,19 +37,14 @@ export const withTimeout = (timeout, signal) => async (cmd, ...args) => {
 
 // A console.log() alternative which can take ProcessOutput.
 export function echo(pieces, ...args) {
-  if (Array.isArray(pieces) && pieces.every(isString) && pieces.length - 1 === args.length) {
-    let msg = pieces[0], i = 0
-    while (i < args.length) {
-      msg += stringify(args[i]) + pieces[++i]
-    }
-    console.log(msg)
+  let msg
+  let lastIdx = pieces.length - 1
+  if (Array.isArray(pieces) && pieces.every(isString) && lastIdx === args.length) {
+    msg = args.map((a, i) => pieces[i] + stringify(a)).join('') + pieces[lastIdx]
   } else {
-    let msg = []
-    for (let it of [pieces, ...args]) {
-      msg.push(it instanceof ProcessOutput ? stringify(it) : it)
-    }
-    console.log(...msg)
+    msg = [pieces, ...args].map(stringify).join(' ')
   }
+  console.log(msg)
 }
 
 function isString(obj) {
test.mjs
@@ -13,7 +13,7 @@
 // limitations under the License.
 
 import {strict as assert} from 'assert'
-import {retry, withTimeout} from './src/experimental.mjs'
+import {retry, echo, startSpinner, withTimeout } from './src/experimental.mjs'
 
 let всегоТестов = 0
 
@@ -249,7 +249,7 @@ if (test('which available')) {
   assert.equal(which.sync('npm'), await which('npm'))
 }
 
-if (test('Retry works')) {
+if (test('Retry works (experimental)')) {
   let exitCode = 0
   let now = Date.now()
   try {
@@ -261,7 +261,7 @@ if (test('Retry works')) {
   assert(Date.now() >= now + 50 * (5 - 1))
 }
 
-if (test('withTimeout works')) {
+if (test('withTimeout works (experimental)')) {
   let exitCode = 0
   let signal
   try {
@@ -274,6 +274,19 @@ if (test('withTimeout works')) {
   assert.equal(signal, 'SIGKILL')
 }
 
+if (test('echo works (experimental)')) {
+  echo(chalk.red('foo'), chalk.green('bar'), chalk.bold('baz'))
+  echo`${chalk.red('foo')} ${chalk.green('bar')} ${chalk.bold('baz')}`
+  echo(await $`echo ${chalk.red('foo')}`, await $`echo ${chalk.green('bar')}`, await $`echo ${chalk.bold('baz')}`)
+}
+
+if (test('spinner works (experimental)')) {
+  let s = startSpinner('waiting')
+
+  await sleep(1000)
+  s()
+}
+
 let version
 if (test('require() is working in ESM')) {
   let data = require('./package.json')
zx.mjs
@@ -21,7 +21,6 @@ import {basename, dirname, extname, join, resolve} from 'path'
 import url from 'url'
 
 import {$, argv, fetch, ProcessOutput, registerGlobals} from './src/index.mjs'
-import which from 'which'
 
 await async function main() {
   registerGlobals()