-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js
71 lines (59 loc) · 2.63 KB
/
common.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
const core = require('@actions/core');
const github = require('@actions/github');
async function cleanCaches(post) {
const asPost = core.getInput('post') === 'true';
if (asPost === !!post) {
try {
const token = core.getInput('token');
const ref = core.getInput('ref');
const except = core.getInput('except');
const include = core.getInput('includePrefix');
const keep = parseInt(core.getInput('keep'), 10);
const octokit = github.getOctokit(token);
console.log(`ref: ${github.context.ref}`)
const branches = [];
if (ref === "") {
if (github.context.payload.pull_request) {
// PR action - process both branch and PR refs
// Fetching the branch name for the PR
const {data: prData} = await octokit.rest.pulls.get({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: github.context.payload.pull_request.number
});
branches.push(`refs/heads/${prData.head.ref}`, `refs/pull/${(github.context.payload.pull_request.number)}/merge`);
} else {
branches.push(github.context.ref)
}
} else {
branches.push(ref);
}
let cachesToDelete = [];
for (const ref of branches) {
const result = await octokit.rest.actions.getActionsCacheList({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
ref: ref
});
const refCaches = result.data.actions_caches
console.log(`Cache keys for ${ref}: ${refCaches.length}`);
cachesToDelete.push(...refCaches);
}
cachesToDelete = cachesToDelete
.sort((a, b) => new Date(b.last_accessed_at) - new Date(a.last_accessed_at))
.filter(cache => cache.key !== except && cache.key.startsWith(include))
.slice(keep);
for (const cache of cachesToDelete) {
console.log(`Deleting cache: ${cache.key}`);
await octokit.rest.actions.deleteActionsCacheById({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
cache_id: cache.id
});
}
} catch (error) {
core.setFailed(error.message);
}
}
}
module.exports = { cleanCaches };