1
1
import { fork } from 'child_process' ;
2
2
import * as path from 'path' ;
3
3
import { Socket } from 'net' ;
4
+ import { Writable } from 'stream' ;
5
+ import * as readline from 'readline' ;
4
6
5
7
let childSpinner = fork ( path . join ( __dirname , 'spinner-child.js' ) ) ;
6
8
childSpinner . unref ( ) ;
9
+
7
10
let childChannel = < Socket > ( < any > childSpinner ) . channel ;
8
11
childChannel . unref ( ) ;
9
12
@@ -39,6 +42,7 @@ export default {
39
42
40
43
let operationsQueue : { operation : string , args : any [ ] } [ ] = [ ] ;
41
44
let inFlight = false ;
45
+ let spinnerIsActive = false ;
42
46
43
47
function queue ( operation : string , ...args : any [ ] ) : void {
44
48
operationsQueue . push ( { operation, args } ) ;
@@ -50,14 +54,39 @@ function flushQueue() {
50
54
return ;
51
55
}
52
56
if ( operationsQueue . length > 0 ) {
53
- inFlight = true ;
54
57
let nextOperation = operationsQueue . shift ( ) ;
58
+ inFlight = true ;
59
+ if ( nextOperation . operation === 'start' ) {
60
+ spinnerIsActive = true ;
61
+ }
55
62
childChannel . ref ( ) ;
56
63
childSpinner . send ( nextOperation ) ;
57
64
childSpinner . once ( 'message' , ( ) => {
58
65
childChannel . unref ( ) ;
59
66
inFlight = false ;
67
+ if ( nextOperation . operation !== 'start' ) {
68
+ spinnerIsActive = false ;
69
+ }
60
70
flushQueue ( ) ;
61
71
} ) ;
62
72
}
63
73
}
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