Commit 0131730

Anton Golub <antongolub@antongolub.com>
2022-06-13 16:52:25
feat: transform some core types into ifaces to let them be extendable by plugins (#439)
* feat: transform some core types into ifaces to let them be extendable in plugins * feat: provide configurable ref for `ctx()`
v6
1 parent 113f6e8
src/context.ts
@@ -15,7 +15,7 @@
 import { AsyncLocalStorage } from 'node:async_hooks'
 import { spawn } from 'node:child_process'
 
-export type Options = {
+export interface Options {
   verbose: boolean | number
   cwd: string
   env: NodeJS.ProcessEnv
@@ -30,7 +30,7 @@ export type Options = {
   logIgnore?: string | string[]
 }
 
-export type Context = Options & {
+export interface Context extends Options {
   nothrow?: boolean
   cmd: string
   __from: string
src/core.ts
@@ -31,7 +31,7 @@ import psTreeModule from 'ps-tree'
 
 const psTree = promisify(psTreeModule)
 
-interface Zx extends Options {
+export interface Zx extends Options {
   (pieces: TemplateStringsArray, ...args: any[]): ProcessPromise
 }
 
src/experimental.ts
@@ -12,7 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-import { ProcessOutput, $ } from './core.js'
+import { ProcessOutput, $, Zx } from './core.js'
 import { sleep } from './goods.js'
 import { isString } from './util.js'
 import { getCtx, runInCtx } from './context.js'
@@ -81,8 +81,8 @@ export function startSpinner(title = '') {
   )(setInterval(spin, 100))
 }
 
-export function ctx<R extends any>(cb: (_$: typeof $) => R): R {
-  const _$ = Object.assign($.bind(null), getCtx())
+export function ctx<R extends any>(cb: (_$: Zx) => R, ref: Zx = $.bind(null)): R {
+  const _$ = Object.assign(ref, getCtx())
 
   return runInCtx(_$, cb, _$)
 }
test/experimental.test.js
@@ -111,6 +111,14 @@ test('ctx() provides isolates running scopes', async () => {
   $.verbose = false
 })
 
+test('ctx accepts optional ref', () => {
+  const ref = $.bind(null)
+
+  ctx(($) => {
+    assert.is(ref, $)
+  }, ref)
+})
+
 test('bound ctx is attached to Promise', async () => {
   const kResourceStoreSymbol = Object.getOwnPropertySymbols(
     new Promise(() => {})
README.md
@@ -502,6 +502,11 @@ ctx(async ($) => {
   // _$.cwd refers to /foo
   // but _$.cwd !== $.cwd
 })
+
+const ref = $.bind(null)
+ctx(($) => {
+  ref === $ // true
+}, ref)
 ```
 
 ### `log()`