import { Worker , isMainThread } from 'worker_threads' ; import workerTask , { WorkerMessage , createErrorMessage } from './worker-task' ; import { resolveConfigurationLocation } from '@config' ; type WorkerCallback < T > = ( worker : Worker ) => T ; type CleanupCallback = ( ) => void ; type EffectCallback = WorkerCallback < CleanupCallback > ; if ( ! isMainThread ) { workerTask ( ) ; } /**
 * Start scanning of given repository in a separate thread
 * - Keeps progress-logger up-to-date via onMessage
 */ function scanRepository ( repository , onMessage , workerCallback ) { return new Promise ( resolve => { onMessage ( { type : 'START' } ) ; const worker = new Worker ( __filename , { workerData : { repository , configurationLocation : resolveConfigurationLocation ( ) , } , env : { ... process . env , GIT_TERMINAL_PROMPT : '0' , } , } ) ; const cleanup = workerCallback ( worker ) ; worker . on ( 'message' , ( message ) => { switch ( message . type ) { case 'LINT_END' : return resolve ( ) ; default : return onMessage ( message ) ; } } ) ; worker . on ( 'error' , ( error ) => { const messages = [ createErrorMessage ( { path : repository , ruleId : '' , message : [ error . code , error . message ] . filter ( Boolean ) . join ( ' ' ) , } ) , ] ; onMessage ( { type : 'WORKER_ERROR' , payload : error . code } ) ; onMessage ( { type : 'ON_RESULT' , payload : { messages } } ) ; resolve ( ) ; } ) ; worker . on ( 'exit' , code => { cleanup ( ) ; if ( code === 0 || code === 1 ) { return resolve ( ) ; } const messages = [ createErrorMessage ( { message : `Worker exited with code ${ code }` , path : repository , ruleId : '' , } ) , ] ; onMessage ( { type : 'ON_RESULT' , payload : { messages } } ) ; resolve ( ) ; } ) ; } ) ; } export default { scanRepository } ;