Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix promise ctx #427

Merged
merged 1 commit into from Jun 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 11 additions & 8 deletions src/core.ts
Expand Up @@ -41,7 +41,7 @@ export const $: Zx = function (pieces: TemplateStringsArray, ...args: any[]) {

let cmd = pieces[0],
i = 0
let quote = getCtx().quote
let quote = promise.ctx.quote
while (i < args.length) {
let s
if (Array.isArray(args[i])) {
Expand All @@ -52,14 +52,12 @@ export const $: Zx = function (pieces: TemplateStringsArray, ...args: any[]) {
cmd += s + pieces[++i]
}

const ctx = {
...getCtx(),
Object.assign(promise.ctx, {
cmd,
__from: new Error().stack!.split(/^\s*at\s/m)[2].trim(),
resolve,
reject,
}
Object.defineProperty(promise, 'ctx', { value: ctx })
})

setImmediate(() => promise._run()) // Make sure all subprocesses are started, if not explicitly by await or then().

Expand Down Expand Up @@ -88,7 +86,12 @@ export class ProcessPromise extends Promise<ProcessOutput> {
_piped = false
_prerun: any = undefined
_postrun: any = undefined
ctx?: Context
readonly ctx: Context
constructor(cb: (resolve: Function, reject?: Function) => void) {
super(cb)
this.ctx = {...getCtx()}
Object.defineProperty(this, 'ctx', { value: this.ctx, writable: false, configurable: false })
}

get stdin() {
this._inheritStdin = false
Expand Down Expand Up @@ -168,7 +171,7 @@ export class ProcessPromise extends Promise<ProcessOutput> {
if (this.child) return // The _run() called from two places: then() and setTimeout().
if (this._prerun) this._prerun() // In case $1.pipe($2), the $2 returned, and on $2._run() invoke $1._run().

runInCtx(this.ctx!, () => {
runInCtx(this.ctx, () => {
const {
nothrow,
cmd,
Expand All @@ -180,7 +183,7 @@ export class ProcessPromise extends Promise<ProcessOutput> {
__from,
resolve,
reject,
} = this.ctx!
} = this.ctx

printCmd(cmd)

Expand Down
11 changes: 11 additions & 0 deletions test/index.test.js
Expand Up @@ -167,6 +167,17 @@ test('ProcessPromise: inherits native Promise', async () => {
assert.ok(p2 !== p3)
assert.ok(p3 !== p4)
assert.ok(p5 !== p1)

assert.ok(p1.ctx)
assert.ok(p2.ctx)
assert.ok(p3.ctx)
assert.ok(p4.ctx)
assert.ok(p5.ctx)

assert.not.equal(p1.ctx, p2.ctx)
assert.equal(p2.ctx, p3.ctx)
assert.equal(p3.ctx, p4.ctx)
assert.equal(p4.ctx, p5.ctx)
})

test('ProcessPromise: ctx is protected from removal', async () => {
Expand Down