import fs from "fs"; import { SyncFoldersFnParams } from "../../types"; import sync from "../../utils/sync"; import SyncScheduler from "../../utils/sync-scheduler"; export default async function watchFolders({ folders, options, }: SyncFoldersFnParams) { const UPDATE_TIMEOUT = 1000; try { const dirs = folders; console.log(`Now handling ${dirs.length} Directories`); /** * # Watch Directories */ const INTERVAL = options?.interval ? options.interval : UPDATE_TIMEOUT; const scheduler = new SyncScheduler( (dirPath, firstRun) => sync({ dirPath, dirs, options, firstRun }), INTERVAL ); for (let i = 0; i < dirs.length; i++) { const dir = dirs[i]; if (!dir) { console.log(`Dir: ${dir} doesn't exist`); continue; } const dirPath = typeof dir == "string" ? dir : dir.path; if ( (typeof dir == "string" && !fs.existsSync(dirPath)) || (typeof dir == "object" && dir.path && !dir.host && !fs.existsSync(dir.path)) ) { console.log(`Dir ${dirPath} does not exist. Creating ...`); try { const existingDirPath = dirs.find((dr) => { if (typeof dr == "string") return fs.existsSync(dr); if (!dr.host) return fs.existsSync(dr.path); // TODO handle remote return false; }); console.log(`Existing Dir to clone: ${existingDirPath}`); if (!existingDirPath) { throw new Error( "No existing Directories for reference" ); } fs.mkdirSync(dirPath, { recursive: true, }); } catch (error: any) { console.log("Error:", error.message); throw new Error( `Folder Doesn't exist and couldn't be created. Please check if Directory exists.\nERROR => ${error.message}` ); } } if (typeof dir == "string") { fs.watch(dirPath, { recursive: true }, (evt, fileName) => { console.log("Folder Changed", evt, fileName); scheduler.schedule(dirPath); }); } } /** * # Sync Last Updated */ const lastUpdatedDir = dirs[0]; const lastUpdatedDirPath = typeof lastUpdatedDir == "string" ? lastUpdatedDir : lastUpdatedDir.path; scheduler.enqueue(lastUpdatedDirPath, true); } catch (error: any) { console.log("ERROR:", error.message); process.exit(0); } }