-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathwith-cache.ts
More file actions
82 lines (68 loc) · 1.78 KB
/
Copy pathwith-cache.ts
File metadata and controls
82 lines (68 loc) · 1.78 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import * as core from "@actions/core";
import * as realCache from "@actions/cache";
import type { CacheKeys } from "./get-cache-keys.js";
export type CacheOptions = {
skipOnHit: boolean;
saveOnError: boolean;
silent: boolean;
};
export const DEFAULT_CACHE_OPTIONS = {
skipOnHit: true,
saveOnError: false,
silent: false,
};
export interface CacheDelegate {
restoreCache: (
paths: string[],
primaryKey: string,
restoreKeys?: string[],
) => Promise<string>;
saveCache: (paths: string[], key: string) => Promise<number>;
}
export async function withCache<T>(
paths: string[],
keys: CacheKeys,
fn: () => Promise<T>,
options: CacheOptions = DEFAULT_CACHE_OPTIONS,
cache?: CacheDelegate,
): Promise<T | undefined> {
const cacheImpl = cache ?? realCache;
const { skipOnHit, saveOnError, silent } = options;
if (!silent) {
core.info(`Cached paths:\n - ${paths.join("\n - ")}`);
core.info(`Cache key: ${keys.primaryKey}`);
core.info(`Cache restore keys:\n - ${keys.restoreKeys.join("\n - ")}`);
}
const restoredKey = await cacheImpl.restoreCache(
paths,
keys.primaryKey,
keys.restoreKeys,
);
const primaryKeyHit = restoredKey == keys.primaryKey;
if (restoredKey) {
if (!silent) {
core.info(`Cache restored from key: ${restoredKey}`);
}
} else {
core.warning("No cache found");
}
if (primaryKeyHit && skipOnHit && !saveOnError) {
if (!silent) {
core.info("Skipping due to primary key hit");
}
return;
}
let result: T;
try {
result = await fn();
if (!primaryKeyHit) {
await cacheImpl.saveCache(paths, keys.primaryKey);
}
} catch (ex) {
if (saveOnError && !primaryKeyHit) {
await cacheImpl.saveCache(paths, keys.primaryKey);
}
throw ex;
}
return result;
}