import * as chokidar from "chokidar" ; import { promises as fsp } from "fs" ; import { parseCrontab } from "./crontab" ; import { ParsedCronItem , SharedOptions , WatchedCronItems } from "./interfaces" ; import { processSharedOptions } from "./lib" ; import { Logger } from "./logger" ; async function loadCrontabIntoCronItems ( logger , items , filename ) { let didntExist = false ; const contents = await fsp . readFile ( filename , "utf8" ) . then ( ( t ) => { if ( didntExist ) { didntExist = false ; logger . info ( `Found crontab file '${ filename }'; cron is now enabled` ) ; } return t ; } ) . catch ( ( e ) => { if ( e . code !== "ENOENT" ) { logger . error ( `Failed to read crontab file '${ filename }': ${ e }` ) ; } else { didntExist = true ; logger . info ( `Failed to read crontab file '${ filename }'; cron is disabled` ) ; } return "" ; } ) ; if ( contents != null ) { const parsed = parseCrontab ( contents ) ; items . splice ( 0 , items . length , ... parsed ) ; } } export default async function getCronItems ( options , crontabPath , watch = false ) { const { logger } = processSharedOptions ( options ) ; let watcher = null ; const items = [ ] ; if ( watch ) { const watchLogger = logger . scope ( { label : "watch" } ) ; watcher = chokidar . watch ( crontabPath , { ignoreInitial : true } ) . on ( "all" , ( ) => { loadCrontabIntoCronItems ( watchLogger , items , crontabPath ) . catch ( ( error ) => { watchLogger . error ( `Error in ${ crontabPath }: ${ error . message }` , { crontabPath , error , } ) ; } ) ; } ) ; } await loadCrontabIntoCronItems ( logger , items , crontabPath ) ; let released = false ; return { items , release : ( ) => { if ( released ) { return ; } released = true ; if ( watcher ) { watcher . close ( ) ; } } , } ; }