From 51fb6d5d710fcd0bfcc7bc905066ac0fa042467c Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Thu, 17 Feb 2022 21:08:16 +0100 Subject: [PATCH] Improve echo --- README.md | 5 ++++- experimental.d.ts | 3 ++- experimental.mjs | 25 +++++++++++++++++-------- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 1392eae199..b3c1c0f318 100644 --- a/README.md +++ b/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 diff --git a/experimental.d.ts b/experimental.d.ts index 273bbf3192..e5a3d6bb12 100644 --- a/experimental.d.ts +++ b/experimental.d.ts @@ -15,7 +15,8 @@ import {ProcessOutput} from './index' interface Echo { - (pieces: TemplateStringsArray, ...args: any[]): Promise + (pieces: TemplateStringsArray, ...args: any[]): void + (...args: any[]): void } interface Retry { diff --git a/experimental.mjs b/experimental.mjs index c1fe615269..5f790020b1 100644 --- a/experimental.mjs +++ b/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) {