import fs from "fs"; import delay from "../../utils/delay"; import { SyncFilesFnParams } from "../../types"; import sync from "../../utils/sync"; export default async function watchFiles({ files, options, }: SyncFilesFnParams) { let timeout: any; const UPDATE_TIMEOUT = 1000; try { for (let i = 0; i < files.length; i++) { const file = files[i]; const filePath = typeof file == "string" ? file : file?.path ? file.path : null; const interval = typeof file == "object" ? file.interval : null; if (!filePath) continue; if (typeof file == "string" && !fs.existsSync(filePath)) { try { const existingFilePath = files.find((fl) => { if (typeof fl == "string") return fs.existsSync(fl); if (!fl.host) return fs.existsSync(fl.path); // TODO handle remote }); if (!existingFilePath) { throw new Error("No existing Files for reference"); } const fileDirPath = typeof existingFilePath == "string" ? existingFilePath : existingFilePath.path; if (!fs.existsSync(fileDirPath)) { fs.mkdirSync(fileDirPath, { recursive: true }); } fs.writeFileSync(filePath, ""); } catch (error: any) { throw new Error( `File Doesn't exist and couldn't be created. Please check if Directory exists.\nERROR => ${error.message}` ); } } if (typeof file == "string" && !fs.statSync(filePath).isFile()) { throw new Error(`'${filePath}' is not a File!`); } if (typeof file == "object" && file.host) { // TODO Handle SSH } else if (typeof file == "string") { await delay(); fs.watchFile( filePath, { interval: interval || 200, }, (curr, prev) => { if (global.SYNCING) return; const INTERVAL = options?.interval ? options.interval : UPDATE_TIMEOUT; clearTimeout(timeout); timeout = setTimeout(() => { global.SYNCING = true; sync({ options, dirPath: filePath, dirs: files, isFiles: true, }).finally(() => { process.exit(global.SYNC_SUCCESS_EXIT_CODE); }); }, INTERVAL); } ); } } const lastUpdatedFile = files[0]; const lastUpdatedFilePath = typeof lastUpdatedFile == "string" ? lastUpdatedFile : lastUpdatedFile.path; global.SYNCING = true; await sync({ dirPath: lastUpdatedFilePath, dirs: files, options, isFiles: true, firstRun: true, }); setTimeout(() => { global.SYNCING = false; }, UPDATE_TIMEOUT); } catch (error: any) { console.log("ERROR:", error.message); process.exit(0); } }