turbo-sync/lib/watch/folders.ts
Benjamin Toby 822778d43b Updates
2025-07-21 13:51:59 +01:00

124 lines
3.7 KiB
TypeScript

import fs from "fs";
import delay from "../../utils/delay";
import { SyncFoldersFnParams } from "../../types";
import sync from "../../utils/sync";
export default async function watchFolders({
folders,
options,
}: SyncFoldersFnParams) {
let timeout: any;
const UPDATE_TIMEOUT = 1000;
try {
const dirs = folders;
console.log("global.SYNCING", global.SYNCING);
console.log(`Now handling ${dirs.length} Directories`);
/**
* # Watch Directories
*/
const INTERVAL = options?.interval ? options.interval : UPDATE_TIMEOUT;
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;
console.log("global.SYNCING", global.SYNCING);
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") {
await delay();
fs.watch(dirPath, { recursive: true }, (evt, fileName) => {
console.log("Folder Changed", evt, fileName);
if (global.SYNCING) {
console.log("Existing Sync found. Returning ...");
return;
}
clearTimeout(timeout);
timeout = setTimeout(() => {
console.log("Folder Syncing in progress ...");
global.SYNCING = true;
sync({ dirPath, dirs, options }).finally(() => {
process.exit(global.SYNC_SUCCESS_EXIT_CODE);
});
}, INTERVAL);
});
}
}
/**
* # Sync Last Updated
*/
const lastUpdatedDir = dirs[0];
const lastUpdatedDirPath =
typeof lastUpdatedDir == "string"
? lastUpdatedDir
: lastUpdatedDir.path;
global.SYNCING = true;
await sync({
dirPath: lastUpdatedDirPath,
dirs,
options,
firstRun: true,
});
setTimeout(() => {
global.SYNCING = false;
}, UPDATE_TIMEOUT);
} catch (error: any) {
console.log("ERROR:", error.message);
process.exit(0);
}
}