setup-uv/src/cache/restore-cache.ts

70 lines
2.1 KiB
TypeScript
Raw Normal View History

import * as cache from "@actions/cache";
import * as glob from "@actions/glob";
import * as core from "@actions/core";
import path from "path";
import {
cacheDependencyGlob,
cacheLocalPath,
cacheSuffix,
} from "../utils/inputs";
import { getArch, getPlatform } from "../utils/platforms";
2024-08-23 23:58:26 +02:00
export const STATE_CACHE_KEY = "cache-key";
export const STATE_CACHE_MATCHED_KEY = "cache-matched-key";
const CACHE_VERSION = "1";
2024-08-23 23:58:26 +02:00
export async function restoreCache(version: string): Promise<void> {
const cacheKey = await computeKeys(version);
2024-08-23 23:58:26 +02:00
let matchedKey: string | undefined;
2024-08-23 23:58:26 +02:00
core.info(
`Trying to restore uv cache from GitHub Actions cache with key: ${cacheKey}`,
);
2024-08-23 23:58:26 +02:00
try {
matchedKey = await cache.restoreCache([cacheLocalPath], cacheKey);
2024-08-23 23:58:26 +02:00
} catch (err) {
const message = (err as Error).message;
core.warning(message);
core.setOutput("cache-hit", false);
return;
2024-08-23 23:58:26 +02:00
}
core.saveState(STATE_CACHE_KEY, cacheKey);
2024-08-23 23:58:26 +02:00
handleMatchResult(matchedKey, cacheKey);
2024-08-23 23:58:26 +02:00
}
async function computeKeys(version: string): Promise<string> {
let cacheDependencyPathHash = "-";
if (cacheDependencyGlob !== "") {
const fullCacheDependencyGlob = `${process.env["GITHUB_WORKSPACE"]}${path.sep}${cacheDependencyGlob}`;
cacheDependencyPathHash += await glob.hashFiles(fullCacheDependencyGlob);
if (cacheDependencyPathHash === "-") {
2024-08-23 23:58:26 +02:00
throw new Error(
`No file in ${process.cwd()} matched to [${cacheDependencyGlob}], make sure you have checked out the target repository`,
);
2024-08-23 23:58:26 +02:00
}
2024-08-24 09:23:57 +02:00
} else {
cacheDependencyPathHash += "no-dependency-glob";
2024-08-23 23:58:26 +02:00
}
const suffix = cacheSuffix ? `-${cacheSuffix}` : "";
return `setup-uv-${CACHE_VERSION}-${getArch()}-${getPlatform()}-${version}${cacheDependencyPathHash}${suffix}`;
2024-08-23 23:58:26 +02:00
}
function handleMatchResult(
matchedKey: string | undefined,
primaryKey: string,
2024-08-23 23:58:26 +02:00
): void {
if (!matchedKey) {
core.info(`No GitHub Actions cache found for key: ${primaryKey}`);
core.setOutput("cache-hit", false);
return;
2024-08-23 23:58:26 +02:00
}
core.saveState(STATE_CACHE_MATCHED_KEY, matchedKey);
2024-08-23 23:58:26 +02:00
core.info(
`uv cache restored from GitHub Actions cache with key: ${matchedKey}`,
);
core.setOutput("cache-hit", true);
2024-08-23 23:58:26 +02:00
}