Skip to content

Commit

Permalink
fix: move promise ctx init point to Promise constructor (#427)
Browse files Browse the repository at this point in the history
  • Loading branch information
antongolub committed Jun 4, 2022
1 parent 3a66988 commit cebe887
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
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

0 comments on commit cebe887

Please sign in to comment.