UNPKG

knip

Version:

Find and fix unused dependencies, exports and files in your TypeScript and JavaScript projects

77 lines (76 loc) 2.07 kB
import { createHash } from 'node:crypto'; import fs from 'node:fs'; import { createDiskCache } from './disk-cache.js'; import { dirname } from './path.js'; const store = createDiskCache('glob'); export const initGlobCache = store.init; export const isGlobCacheEnabled = store.isEnabled; export const flushGlobCache = store.flush; export const clearGlobCache = store.clear; export const computeGlobCacheKey = (input) => { const h = createHash('sha1'); h.update(input.cwd); h.update('\0'); h.update(input.dir); h.update('\0'); h.update(input.gitignore ? '1' : '0'); h.update('\0'); for (const p of input.patterns) { h.update(p); h.update('\0'); } return h.digest('base64url'); }; const validateEntry = (entry) => { for (const dir in entry.dirMtimes) { try { const stat = fs.statSync(dir); if (stat.mtimeMs !== entry.dirMtimes[dir]) return false; } catch { return false; } } return true; }; export const getCachedGlob = (key) => { const entry = store.get(key); if (!entry) return undefined; if (!validateEntry(entry)) { store.delete(key); return undefined; } return entry.paths; }; const captureDirMtimes = (paths, baseDir) => { const dirs = new Set(); dirs.add(baseDir); for (const p of paths) { let d = dirname(p); while (d.length >= baseDir.length) { if (dirs.has(d)) break; dirs.add(d); const parent = dirname(d); if (parent === d) break; d = parent; } } const result = {}; for (const d of dirs) { try { const stat = fs.statSync(d); if (stat.isDirectory()) result[d] = stat.mtimeMs; } catch { } } return result; }; export const setCachedGlob = (key, paths, baseDir) => { store.set(key, { paths, dirMtimes: captureDirMtimes(paths, baseDir) }); };