import * as cache from '@actions/cache';
import * as core from '@actions/core';
import * as glob from '@actions/glob';
import { readFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
export class GitHubCacheCapability {
    pendingCaches = [];
    async mount(ref) {
        const path = ref.mountPath;
        if (!path) {
            throw new Error(`Cache "${ref.name}" has no mount path`);
        }
        const key = await this.computeKey(ref);
        const restoreKeys = this.computeRestoreKeys(ref);
        const restoredKey = await cache.restoreCache([path], key, restoreKeys);
        const hit = restoredKey !== undefined;
        if (hit) {
            core.info(`Cache hit: ${restoredKey}`);
        }
        else {
            core.info(`Cache miss, will save as: ${key}`);
        }
        // Track for post-run save
        this.pendingCaches.push({ paths: [path], key, restoredKey });
        process.env.KITSI_PENDING_CACHES = JSON.stringify(this.pendingCaches);
        return hit;
    }
    async computeKey(ref) {
        const parts = [process.env.RUNNER_OS ?? 'unknown', ref.name];
        const key = ref.key;
        if (key?.files && key.files.length > 0) {
            const hash = await this.hashFiles(key.files);
            parts.push(hash.slice(0, 16));
        }
        if (key?.env && key.env.length > 0) {
            const hash = this.hashEnv(key.env);
            parts.push(hash.slice(0, 16));
        }
        if (key?.value) {
            const hash = this.hashValue(key.value);
            parts.push(hash.slice(0, 16));
        }
        return parts.join('-');
    }
    async hashFiles(patterns) {
        const globber = await glob.create(patterns.join('\n'));
        const files = await globber.glob();
        const hash = createHash('sha256');
        for (const file of files.sort()) {
            const contents = await readFile(file);
            hash.update(file);
            hash.update(contents);
        }
        return hash.digest('hex');
    }
    hashEnv(names) {
        const hash = createHash('sha256');
        for (const name of names.sort()) {
            hash.update(name);
            hash.update('=');
            hash.update(process.env[name] ?? '__unset__');
        }
        return hash.digest('hex');
    }
    hashValue(value) {
        return createHash('sha256').update(value).digest('hex');
    }
    computeRestoreKeys(ref) {
        return [`${process.env.RUNNER_OS ?? 'unknown'}-${ref.name}-`];
    }
    getPendingCaches() {
        return this.pendingCaches;
    }
}
//# sourceMappingURL=cache.js.map