Commit 2ec108e
Changed files (3)
src/core.ts
@@ -329,8 +329,8 @@ export function quiet(promise: ProcessPromise) {
return promise
}
-export function within(callback: () => void) {
+export function within<R>(callback: (...args: any) => R): R {
let context = storage.getStore()
assert(context)
- storage.run({ ...context }, callback)
+ return storage.run({ ...context }, callback)
}
test/index.test.js
@@ -381,6 +381,27 @@ test('within() restores previous cwd', async () => {
await promise
})
+test(`within() isolates nested context and returns cb result`, async () => {
+ within(async () => {
+ const res = await within(async () => {
+ $.verbose = true
+
+ return within(async () => {
+ assert.equal($.verbose, true)
+ $.verbose = false
+
+ return within(async () => {
+ assert.equal($.verbose, false)
+ $.verbose = true
+ return 'foo'
+ })
+ })
+ })
+ assert.equal($.verbose, false)
+ assert.equal(res, 'foo')
+ })
+})
+
test('spinner works', async () => {
let s = startSpinner('waiting')
await sleep(1000)
README.md
@@ -269,6 +269,21 @@ await $`pwd` // => /home/path
assert($.verbose == true)
```
+Building profiled commands stack:
+
+ ```js
+const nodev = async (v) => within(async () => {
+ $.verbose = false
+ $.prefix += 'export NVM_DIR=$HOME/.nvm; source $NVM_DIR/nvm.sh; '
+
+ await $`nvm use ${v}`
+
+ return $`node -v`.then(r => r.stdout.trim().slice(1)) // 'v18.0.0\n' → '18.0.0'
+})
+
+await nodev(18) // '18.0.0'
+````
+
## Packages
Following packages are available without importing inside scripts.