From 0a2f18d98f1e94cfb9f630802b4518dbfb4254a7 Mon Sep 17 00:00:00 2001 From: Anton Date: Thu, 26 Oct 2023 15:34:32 +0300 Subject: [PATCH] feat: provide `$.trim` option https://github.com/google/zx/issues/690 --- README.md | 3 +++ src/main/js/index.mjs | 15 ++++++++++++++- src/test/js/test.mjs | 22 ++++++++++++++++++++-- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 81b0ea6..032a789 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/main/js/index.mjs b/src/main/js/index.mjs index f6bb747..073c846 100644 --- a/src/main/js/index.mjs +++ b/src/main/js/index.mjs @@ -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' @@ -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) { @@ -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 diff --git a/src/test/js/test.mjs b/src/test/js/test.mjs index 788f5de..9a5b205 100644 --- a/src/test/js/test.mjs +++ b/src/test/js/test.mjs @@ -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