website

#astro#js#html#css

git clone https://git.pyrossh.dev/website

木 Personal website of pyrossh. Built with astrojs, shiki, vite.


src/_helpers/dataCache.js
ada6e53 1
import fs from "node:fs";
ada6e53 2
import path from "node:path";
ada6e53 3
import { fileURLToPath } from "node:url";
ada6e53 4
ada6e53 5
const __dirname = path.dirname(fileURLToPath(import.meta.url));
ada6e53 6
const CACHE_DIR = path.resolve(__dirname, "..", "..", ".cache");
ada6e53 7
ada6e53 8
const cachePath = (key) => path.join(CACHE_DIR, `${key}.json`);
ada6e53 9
ada6e53 10
/**
ada6e53 11
 * Disk cache for the expensive per-commit/per-file git data (diffs,
ada6e53 12
 * history, blame, syntax highlighting) computed in repoCommits.js/
ada6e53 13
 * repoFiles.js. Keyed by the repo's current HEAD sha rather than by
ada6e53 14
 * content hash — cheap to check (one `git rev-parse` per repo) and
ada6e53 15
 * correct as long as callers only read the cache for a clean working
ada6e53 16
 * tree (see isDirty() in gitRepos.js): if HEAD hasn't moved and there
ada6e53 17
 * are no uncommitted changes, none of this data could have changed.
ada6e53 18
 */
ada6e53 19
export const readCache = (key, sha) => {
ada6e53 20
  try {
ada6e53 21
    const { sha: cachedSha, data } = JSON.parse(fs.readFileSync(cachePath(key), "utf8"));
ada6e53 22
    return cachedSha === sha ? data : null;
ada6e53 23
  } catch {
ada6e53 24
    return null;
ada6e53 25
  }
ada6e53 26
};
ada6e53 27
ada6e53 28
export const writeCache = (key, sha, data) => {
ada6e53 29
  try {
ada6e53 30
    fs.mkdirSync(CACHE_DIR, { recursive: true });
ada6e53 31
    fs.writeFileSync(cachePath(key), JSON.stringify({ sha, data }));
ada6e53 32
  } catch {
ada6e53 33
    // best-effort — a failed cache write shouldn't fail the build
ada6e53 34
  }
ada6e53 35
};