Debian Codegraph @

packages/babel-core/src/config/files/utils.ts

raw
1 import type { Handler } from "gensync";
2
3 import { makeStrongCache } from "../caching";
4 import type { CacheConfigurator } from "../caching";
5 import * as fs from "../../gensync-utils/fs";
6 import nodeFs from "fs";
7
8 export function makeStaticFileCache<T>(
9 fn: (filepath: string, contents: string) => T,
10 ) {
11 return makeStrongCache(function* (
12 filepath: string,
13 cache: CacheConfigurator<void>,
14 ): Handler<null | T> {
15 const cached = cache.invalidate(() => fileMtime(filepath));
16
17 if (cached === null) {
18 return null;
19 }
20
21 return fn(filepath, yield* fs.readFile(filepath, "utf8"));
22 });
23 }
24
25 function fileMtime(filepath: string): number | null {
26 if (!nodeFs.existsSync(filepath)) return null;
27
28 try {
29 return +nodeFs.statSync(filepath).mtime;
30 } catch (e) {
31 if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e;
32 }
33
34 return null;
35 }