-
Notifications
You must be signed in to change notification settings - Fork 355
/
Copy pathdependency-caching.js
218 lines (218 loc) · 9.47 KB
/
dependency-caching.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getJavaTempDependencyDir = getJavaTempDependencyDir;
exports.downloadDependencyCaches = downloadDependencyCaches;
exports.uploadDependencyCaches = uploadDependencyCaches;
const os = __importStar(require("os"));
const path_1 = require("path");
const actionsCache = __importStar(require("@actions/cache"));
const glob = __importStar(require("@actions/glob"));
const actions_util_1 = require("./actions-util");
const caching_utils_1 = require("./caching-utils");
const environment_1 = require("./environment");
const util_1 = require("./util");
const CODEQL_DEPENDENCY_CACHE_PREFIX = "codeql-dependencies";
const CODEQL_DEPENDENCY_CACHE_VERSION = 1;
/**
* Returns a path to a directory intended to be used to store .jar files
* for the Java `build-mode: none` extractor.
* @returns The path to the directory that should be used by the `build-mode: none` extractor.
*/
function getJavaTempDependencyDir() {
return (0, path_1.join)((0, actions_util_1.getTemporaryDirectory)(), "codeql_java", "repository");
}
/**
* Default caching configurations per language.
*/
const CODEQL_DEFAULT_CACHE_CONFIG = {
java: {
paths: [
// Maven
(0, path_1.join)(os.homedir(), ".m2", "repository"),
// Gradle
(0, path_1.join)(os.homedir(), ".gradle", "caches"),
// CodeQL Java build-mode: none
getJavaTempDependencyDir(),
],
hash: [
// Maven
"**/pom.xml",
// Gradle
"**/*.gradle*",
"**/gradle-wrapper.properties",
"buildSrc/**/Versions.kt",
"buildSrc/**/Dependencies.kt",
"gradle/*.versions.toml",
"**/versions.properties",
],
},
csharp: {
paths: [(0, path_1.join)(os.homedir(), ".nuget", "packages")],
hash: [
// NuGet
"**/packages.lock.json",
// Paket
"**/paket.lock",
],
},
go: {
paths: [(0, path_1.join)(os.homedir(), "go", "pkg", "mod")],
hash: ["**/go.sum"],
},
};
async function makeGlobber(patterns) {
return glob.create(patterns.join("\n"));
}
/**
* Attempts to restore dependency caches for the languages being analyzed.
*
* @param languages The languages being analyzed.
* @param logger A logger to record some informational messages to.
* @returns A list of languages for which dependency caches were restored.
*/
async function downloadDependencyCaches(languages, logger) {
const restoredCaches = [];
for (const language of languages) {
const cacheConfig = CODEQL_DEFAULT_CACHE_CONFIG[language];
if (cacheConfig === undefined) {
logger.info(`Skipping download of dependency cache for ${language} as we have no caching configuration for it.`);
continue;
}
// Check that we can find files to calculate the hash for the cache key from, so we don't end up
// with an empty string.
const globber = await makeGlobber(cacheConfig.hash);
if ((await globber.glob()).length === 0) {
logger.info(`Skipping download of dependency cache for ${language} as we cannot calculate a hash for the cache key.`);
continue;
}
const primaryKey = await cacheKey(language, cacheConfig);
const restoreKeys = [await cachePrefix(language)];
logger.info(`Downloading cache for ${language} with key ${primaryKey} and restore keys ${restoreKeys.join(", ")}`);
const hitKey = await actionsCache.restoreCache(cacheConfig.paths, primaryKey, restoreKeys);
if (hitKey !== undefined) {
logger.info(`Cache hit on key ${hitKey} for ${language}.`);
restoredCaches.push(language);
}
else {
logger.info(`No suitable cache found for ${language}.`);
}
}
return restoredCaches;
}
/**
* Attempts to store caches for the languages that were analyzed.
*
* @param config The configuration for this workflow.
* @param logger A logger to record some informational messages to.
*/
async function uploadDependencyCaches(config, logger) {
for (const language of config.languages) {
const cacheConfig = CODEQL_DEFAULT_CACHE_CONFIG[language];
if (cacheConfig === undefined) {
logger.info(`Skipping upload of dependency cache for ${language} as we have no caching configuration for it.`);
continue;
}
// Check that we can find files to calculate the hash for the cache key from, so we don't end up
// with an empty string.
const globber = await makeGlobber(cacheConfig.hash);
if ((await globber.glob()).length === 0) {
logger.info(`Skipping upload of dependency cache for ${language} as we cannot calculate a hash for the cache key.`);
continue;
}
// Calculate the size of the files that we would store in the cache. We use this to determine whether the
// cache should be saved or not. For example, if there are no files to store, then we skip creating the
// cache. In the future, we could also:
// - Skip uploading caches with a size below some threshold: this makes sense for avoiding the overhead
// of storing and restoring small caches, but does not help with alert wobble if a package repository
// cannot be reached in a given run.
// - Skip uploading caches with a size above some threshold: this could be a concern if other workflows
// use the cache quota that we compete with. In that case, we do not wish to use up all of the quota
// with the dependency caches. For this, we could use the Cache API to check whether other workflows
// are using the quota and how full it is.
const size = await (0, caching_utils_1.getTotalCacheSize)(cacheConfig.paths, logger, true);
// Skip uploading an empty cache.
if (size === 0) {
logger.info(`Skipping upload of dependency cache for ${language} since it is empty.`);
continue;
}
const key = await cacheKey(language, cacheConfig);
logger.info(`Uploading cache of size ${size} for ${language} with key ${key}...`);
try {
await actionsCache.saveCache(cacheConfig.paths, key);
}
catch (error) {
// `ReserveCacheError` indicates that the cache key is already in use, which means that a
// cache with that key already exists or is in the process of being uploaded by another
// workflow. We can ignore this.
if (error instanceof actionsCache.ReserveCacheError) {
logger.info(`Not uploading cache for ${language}, because ${key} is already in use.`);
logger.debug(error.message);
}
else {
// Propagate other errors upwards.
throw error;
}
}
}
}
/**
* Computes a cache key for the specified language.
*
* @param language The language being analyzed.
* @param cacheConfig The cache configuration for the language.
* @returns A cache key capturing information about the project(s) being analyzed in the specified language.
*/
async function cacheKey(language, cacheConfig) {
const hash = await glob.hashFiles(cacheConfig.hash.join("\n"));
return `${await cachePrefix(language)}${hash}`;
}
/**
* Constructs a prefix for the cache key, comprised of a CodeQL-specific prefix, a version number that
* can be changed to invalidate old caches, the runner's operating system, and the specified language name.
*
* @param language The language being analyzed.
* @returns The prefix that identifies what a cache is for.
*/
async function cachePrefix(language) {
const runnerOs = (0, util_1.getRequiredEnvParam)("RUNNER_OS");
const customPrefix = process.env[environment_1.EnvVar.DEPENDENCY_CACHING_PREFIX];
let prefix = CODEQL_DEPENDENCY_CACHE_PREFIX;
if (customPrefix !== undefined && customPrefix.length > 0) {
prefix = `${prefix}-${customPrefix}`;
}
return `${prefix}-${CODEQL_DEPENDENCY_CACHE_VERSION}-${runnerOs}-${language}-`;
}
//# sourceMappingURL=dependency-caching.js.map