Skip to content

Commit daf72bb

Browse files
committed
feat: ensure spinner does not interfere with other process output
1 parent 079e5c1 commit daf72bb

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

lib/spinner.ts

+30-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import { fork } from 'child_process';
22
import * as path from 'path';
33
import { Socket } from 'net';
4+
import { Writable } from 'stream';
5+
import * as readline from 'readline';
46

57
let childSpinner = fork(path.join(__dirname, 'spinner-child.js'));
68
childSpinner.unref();
9+
710
let childChannel = <Socket>(<any>childSpinner).channel;
811
childChannel.unref();
912

@@ -39,6 +42,7 @@ export default {
3942

4043
let operationsQueue: { operation: string, args: any[] }[] = [];
4144
let inFlight = false;
45+
let spinnerIsActive = false;
4246

4347
function queue(operation: string, ...args: any[]): void {
4448
operationsQueue.push({ operation, args });
@@ -50,14 +54,39 @@ function flushQueue() {
5054
return;
5155
}
5256
if (operationsQueue.length > 0) {
53-
inFlight = true;
5457
let nextOperation = operationsQueue.shift();
58+
inFlight = true;
59+
if (nextOperation.operation === 'start') {
60+
spinnerIsActive = true;
61+
}
5562
childChannel.ref();
5663
childSpinner.send(nextOperation);
5764
childSpinner.once('message', () => {
5865
childChannel.unref();
5966
inFlight = false;
67+
if (nextOperation.operation !== 'start') {
68+
spinnerIsActive = false;
69+
}
6070
flushQueue();
6171
});
6272
}
6373
}
74+
75+
export function wrapOutputStream(stream: Writable) {
76+
let originalWrite = stream.write.bind(stream);
77+
let mockOriginalStream = <any>{ write: originalWrite };
78+
stream.write = function wrappedWrite(chunk: any, encoding?: any, callback?: any) {
79+
if (spinnerIsActive) {
80+
readline.clearLine(mockOriginalStream, 0);
81+
readline.cursorTo(mockOriginalStream, 0);
82+
chunk = chunk.toString();
83+
if (!chunk.endsWith('\n')) {
84+
chunk = chunk + '\n';
85+
}
86+
}
87+
return originalWrite(chunk, encoding, callback);
88+
};
89+
}
90+
91+
wrapOutputStream(<any>process.stdout);
92+
wrapOutputStream(<any>process.stderr);

0 commit comments

Comments
 (0)