Commit 69de40d

Anton Medvedev <anton@medv.io>
2021-05-05 23:30:26
Add better command substitution
1 parent 9b801b4
examples/basics.mjs
@@ -14,12 +14,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-await $`# Hello world!
-date
-`
+await $`ls -1 | wc -l`
 
-let answer = await question('What is your name? ')
-await $`echo "Hello, ${answer}!"`
+let branch = await $`git branch --show-current`
+await $`printf ${branch} | wc`
 
 if (test('-f package.json')) {
   console.log('Yes')
index.mjs
@@ -27,10 +27,17 @@ function colorize(cmd) {
   })
 }
 
+function substitute(arg) {
+  if (arg instanceof ProcessOutput) {
+    return arg.stdout.replace(/\n$/, '')
+  }
+  return arg
+}
+
 export function $(pieces, ...args) {
   let __from = (new Error().stack.split('at ')[2]).trim()
   let cmd = pieces[0], i = 0
-  for (; i < args.length; i++) cmd += args[i] + pieces[i + 1]
+  for (; i < args.length; i++) cmd += substitute(args[i]) + pieces[i + 1]
   for (++i; i < pieces.length; i++) cmd += pieces[i]
 
   if ($.verbose) console.log('$', colorize(cmd))
@@ -130,15 +137,15 @@ export class ProcessOutput {
   }
 
   toString() {
-    return this.#combined.replace(/\n$/, '')
+    return this.#combined
   }
 
   get stdout() {
-    return this.#stdout.replace(/\n$/, '')
+    return this.#stdout
   }
 
   get stderr() {
-    return this.#stderr.replace(/\n$/, '')
+    return this.#stderr
   }
 
   get exitCode() {
package.json
@@ -1,7 +1,7 @@
 {
   "name": "zx",
-  "version": "1.0.1",
-  "description": "Replaces bash with js",
+  "version": "1.0.2",
+  "description": "A tool for writing better scripts",
   "main": "index.mjs",
   "types": "index.d.ts",
   "bin": {
test.mjs
@@ -12,6 +12,9 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+let foo = await $`echo Error >&2; echo Hello`
+await $`echo ${foo} | wc`
+
 await Promise.all([
   $`sleep 1; echo 1`,
   $`sleep 2; echo 2`,