All files cache.ts

7.69% Statements 1/13
0% Branches 0/4
0% Functions 0/4
8.33% Lines 1/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35        1x                                                            
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { join, dirname } from 'node:path';
 
export const DEFAULT_CACHE_FILENAME = '.contractkit-cache';
 
export interface FileHashMap {
    [filePath: string]: string; // path -> sha256 hex
}
 
export function computeHash(content: string): string {
    return createHash('sha256').update(content).digest('hex');
}
 
export function loadCache(dir: string, filename: string = DEFAULT_CACHE_FILENAME): FileHashMap {
    const cachePath = join(dir, filename);
    try {
        return JSON.parse(readFileSync(cachePath, 'utf-8'));
    } catch {
        return {};
    }
}
 
export function saveCache(dir: string, cache: FileHashMap, filename: string = DEFAULT_CACHE_FILENAME): void {
    const cachePath = join(dir, filename);
    mkdirSync(dirname(cachePath), { recursive: true });
    writeFileSync(cachePath, JSON.stringify(cache, null, 2), 'utf-8');
}
 
export function isFileChanged(filePath: string, content: string, outPath: string, cache: FileHashMap): boolean {
    if (!existsSync(outPath)) return true;
    const currentHash = computeHash(content);
    return cache[filePath] !== currentHash;
}