Skip to content

Commit

Permalink
Improve echo
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Feb 17, 2022
1 parent 59e9121 commit 51fb6d5
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
5 changes: 4 additions & 1 deletion README.md
Expand Up @@ -354,15 +354,18 @@ import {retry} from 'zx/experimental'
let {stdout} = await retry(5)`curl localhost`
```
#### ``echo`...` ``
#### `echo()`
A `console.log()` alternative which can take [ProcessOutput](#processoutput).
```js
import {echo} from 'zx/experimental'

let branch = await $`git branch --show-current`

echo`Current branch is ${branch}.`
// or
echo('Current branch is', branch)
```
### FAQ
Expand Down
3 changes: 2 additions & 1 deletion experimental.d.ts
Expand Up @@ -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 {
Expand Down
25 changes: 17 additions & 8 deletions experimental.mjs
Expand Up @@ -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) {
Expand Down

0 comments on commit 51fb6d5

Please sign in to comment.