Skip to content

Commit

Permalink
feat: provide $.trim option
Browse files Browse the repository at this point in the history
  • Loading branch information
antongolub committed Oct 26, 2023
1 parent fbac64a commit 0a2f18d
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ const output = (await $.raw`${cmd} ${msg}`).toString().trim()
### `$.verbose`
Set to `false` by default.

### `$.trim`
Applies `.thim()` to `ProcessOutput` string representation. Set `true` by default.

### `$.opt`
Returns `$` with the specified preset. Aliased for `$.o`.
```js
Expand Down
15 changes: 14 additions & 1 deletion src/main/js/index.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {$ as _$, quiet, ProcessPromise, within} from 'zx'
import {$ as _$, quiet, ProcessPromise, within, ProcessOutput} from 'zx'
import childProcess from 'node:child_process'
import {isTemplateSignature, randomId} from './util.mjs'
import {npmRunPath} from 'npm-run-path'
Expand All @@ -8,6 +8,17 @@ import {semver} from './goods.mjs'
export * from 'zx'
export * from './goods.mjs'

ProcessOutput.prototype.valueOf = function () {
return this.toString()
}

ProcessOutput.prototype.toString = function () {
const str = this._combined.toString()
return $.trim
? str.trim()
: str
}

export const $ = new DeepProxy(_$, ({DEFAULT, target: t, trapName, args}) => {
if (trapName === 'apply') {
if (!t.preferLocal) {
Expand All @@ -29,6 +40,8 @@ export const ctx = (cb, ref = $) => within(() => cb(ref))

$.verbose = false

$.trim = true

$.raw = async (...args) => $.o({quote: v => v})(...args)

// https://github.com/google/zx/pull/134
Expand Down
22 changes: 20 additions & 2 deletions src/test/js/test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,30 @@ import {
assert($.verbose === false)
}

// $.trim
{
$.trim = false
const _output = await $`echo foobar`

assert(_output.toString() !== 'foobar')
assert(_output.toString().trim() === 'foobar')

$.trim = true
const output = await $`echo foobar`

assert(output.toString() === 'foobar')
assert(output == 'foobar')
assert(/foo/.test(output))
assert(`${output}baz` === 'foobarbaz')
}

// $.raw
{
const cmd = 'echo raw foo'
const msg = 'bar'
const output = (await $.raw`${cmd} ${msg}`).toString().trim()
assert(output === 'raw foo bar')
const output = await $.raw`${cmd} ${msg}`

assert(output.toString().trim() === 'raw foo bar')
}

// $.silent
Expand Down

0 comments on commit 0a2f18d

Please sign in to comment.