Skip to content

Commit

Permalink
feat: transform some core types into ifaces to let them be extendable…
Browse files Browse the repository at this point in the history
… by plugins (#439)

* feat: transform some core types into ifaces to let them be extendable in plugins

* feat: provide configurable ref for `ctx()`
  • Loading branch information
antongolub committed Jun 13, 2022
1 parent 113f6e8 commit 0131730
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 6 deletions.
5 changes: 5 additions & 0 deletions README.md
Expand Up @@ -502,6 +502,11 @@ ctx(async ($) => {
// _$.cwd refers to /foo
// but _$.cwd !== $.cwd
})

const ref = $.bind(null)
ctx(($) => {
ref === $ // true
}, ref)
```
### `log()`
Expand Down
4 changes: 2 additions & 2 deletions src/context.ts
Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/core.ts
Expand Up @@ -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
}

Expand Down
6 changes: 3 additions & 3 deletions src/experimental.ts
Expand Up @@ -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'
Expand Down Expand Up @@ -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, _$)
}
8 changes: 8 additions & 0 deletions test/experimental.test.js
Expand Up @@ -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(() => {})
Expand Down

0 comments on commit 0131730

Please sign in to comment.