Commit 51fb6d5

Anton Medvedev <anton@medv.io>
2022-02-17 21:08:16
Improve echo
1 parent 59e9121
experimental.d.ts
@@ -15,7 +15,8 @@
 import {ProcessOutput} from './index'
 
 interface Echo {
-  (pieces: TemplateStringsArray, ...args: any[]): Promise<void>
+  (pieces: TemplateStringsArray, ...args: any[]): void
+  (...args: any[]): void
 }
 
 interface Retry {
experimental.mjs
@@ -25,15 +25,24 @@ export const retry = (count = 5) => async (cmd, ...args) => {
 }
 
 // A console.log() alternative which can take ProcessOutput.
-export const echo = (pieces, ...args) => {
-  if (!Array.isArray(pieces) || pieces.length - 1 !== args.length) {
-    throw new Error('The echo is a template string. Use as echo`...`.')
+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)
+  } else {
+    let msg = []
+    for (let it of [pieces, ...args]) {
+      msg.push(it instanceof ProcessOutput ? stringify(it) : it)
+    }
+    console.log(...msg)
   }
-  let msg = pieces[0], i = 0
-  while (i < args.length) {
-    msg += stringify(args[i]) + pieces[++i]
-  }
-  console.log(msg)
+}
+
+function isString(obj) {
+  return typeof obj === 'string'
 }
 
 function stringify(arg) {
README.md
@@ -354,7 +354,7 @@ import {retry} from 'zx/experimental'
 let {stdout} = await retry(5)`curl localhost`
 ```
 
-#### ``echo`...` ``
+#### `echo()`
 
 A `console.log()` alternative which can take [ProcessOutput](#processoutput).
 
@@ -362,7 +362,10 @@ A `console.log()` alternative which can take [ProcessOutput](#processoutput).
 import {echo} from 'zx/experimental'
 
 let branch = await $`git branch --show-current`
+
 echo`Current branch is ${branch}.`
+// or
+echo('Current branch is', branch)
 ```
 
 ### FAQ