@@ -25,21 +25,42 @@ interface SpawnOptions {
2525}
2626
2727export function spawnAsync ( cmd : string , options ?: SpawnOptions , input ?: string ) : Promise < SpawnAsync > {
28- const start = Date . now ( ) ;
28+ const timeoutMs = options ?. timeout || 60_000 * 5 ;
2929
3030 return new Promise < SpawnAsync > ( resolve => {
3131 const cp = childProcess . spawn ( cmd , { shell : true , ...options } ) ;
3232
3333 // Ensure we properly time out after max. 5 min per command
34- const timeout = setTimeout ( ( ) => {
34+ let timeout : ReturnType < typeof setTimeout > | undefined = setTimeout ( ( ) => {
3535 console . log ( `Command "${ cmd } " timed out after 5 minutes.` ) ;
3636 cp . kill ( ) ;
37- } , 5 * 60_000 ) ;
37+ end ( null , `ETDIMEDOUT: Process timed out after ${ timeoutMs } ms.` ) ;
38+ } , timeoutMs ) ;
3839
3940 const stderr : unknown [ ] = [ ] ;
4041 const stdout : string [ ] = [ ] ;
4142 let error : Error | undefined ;
4243
44+ function end ( status : number | null , errorMessage ?: string ) : void {
45+ // This means we already ended
46+ if ( ! timeout ) {
47+ return ;
48+ }
49+
50+ if ( ! error && errorMessage ) {
51+ error = new Error ( errorMessage ) ;
52+ }
53+
54+ clearTimeout ( timeout ) ;
55+ timeout = undefined ;
56+ resolve ( {
57+ stdout : stdout . join ( '' ) ,
58+ stderr : stderr . join ( '' ) ,
59+ error : error || ( status !== 0 ? new Error ( `Process exited with status ${ status } ` ) : undefined ) ,
60+ status,
61+ } ) ;
62+ }
63+
4364 cp . stdout . on ( 'data' , data => {
4465 stdout . push ( data ? ( data as object ) . toString ( ) : '' ) ;
4566 } ) ;
@@ -53,20 +74,7 @@ export function spawnAsync(cmd: string, options?: SpawnOptions, input?: string):
5374 } ) ;
5475
5576 cp . on ( 'close' , status => {
56- const end = Date . now ( ) ;
57-
58- // We manually mark this as timed out if the process takes too long
59- if ( ! error && status === 1 && options ?. timeout && end >= start + options . timeout ) {
60- error = new Error ( `ETDIMEDOUT: Process timed out after ${ options . timeout } ms.` ) ;
61- }
62-
63- clearTimeout ( timeout ) ;
64- resolve ( {
65- stdout : stdout . join ( '' ) ,
66- stderr : stderr . join ( '' ) ,
67- error : error || ( status !== 0 ? new Error ( `Process exited with status ${ status } ` ) : undefined ) ,
68- status,
69- } ) ;
77+ end ( status ) ;
7078 } ) ;
7179
7280 if ( input ) {
0 commit comments