turbo-sync/utils/get-last-edited-src.ts
Benjamin Toby 822778d43b Updates
2025-07-21 13:51:59 +01:00

68 lines
1.7 KiB
TypeScript

import fs from "fs";
import path from "path";
type Params = {
dirs?: string[];
files?: string[];
};
export default function getLatestSource({
dirs,
files,
}: Params): string | undefined {
let latestDir = undefined;
let latestMtime = 0;
const isFiles = files?.[0];
const finalPaths = isFiles ? files : dirs;
if (!finalPaths) return undefined;
for (const pth of finalPaths) {
try {
const stats = fs.statSync(pth);
const pathMtime = stats.isDirectory()
? getLatestDirMtime(pth)
: stats.mtimeMs;
if (pathMtime > latestMtime) {
latestMtime = pathMtime;
latestDir = pth;
}
} catch (error: any) {
console.error(`Error accessing ${pth}: ${error.message}`);
}
}
return latestDir;
}
function getLatestDirMtime(dir: string) {
let latestMtime = 0;
try {
const stats = fs.statSync(dir);
if (stats.isDirectory()) {
latestMtime = stats.mtimeMs;
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const entryPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
const subMtime = getLatestDirMtime(entryPath);
latestMtime = Math.max(latestMtime, subMtime);
} else if (entry.isFile()) {
const fileStats = fs.statSync(entryPath);
latestMtime = Math.max(latestMtime, fileStats.mtimeMs);
}
}
}
} catch (error: any) {
console.error(`Error accessing ${dir}: ${error.message}`);
}
return latestMtime;
}