-
Notifications
You must be signed in to change notification settings - Fork 0
114 lines (100 loc) · 3.65 KB
/
cache-cleanup.yaml
File metadata and controls
114 lines (100 loc) · 3.65 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
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
name: Cache Cleanup
on:
schedule:
- cron: 0 0 * * *
pull_request:
types:
- closed
workflow_dispatch:
inputs:
dryrun:
type: boolean
description: "Perform a dry run without deleting caches"
default: true
permissions:
actions: write
jobs:
cleanup:
runs-on: ubuntu-latest
steps:
- name: Delete old caches
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const perPage = 100;
const maxPages = 10;
let page = 1;
let allCaches = [];
const getType = key => {
if (key.startsWith('v0-rust')) return key.split('-').slice(0, -2).join('-');
if (key.startsWith('node-cache')) return key.split('-').slice(0, -1).join('-');
return key;
};
const isBranchExists = async branchName => {
try {
await github.rest.repos.getBranch({
owner: context.repo.owner,
repo: context.repo.repo,
branch: branchName,
});
return true;
} catch (error) {
if (error.status === 404) {
return false;
} else {
throw error;
}
}
};
const getBranchNameFromRef = ref => ref.split('/').slice(2).join('/');
while (page <= maxPages) {
const response = await github.rest.actions.getActionsCacheList({
owner: context.repo.owner,
repo: context.repo.repo,
per_page: perPage,
page,
});
allCaches = allCaches.concat(response.data.actions_caches);
if (response.data.actions_caches.length < perPage) {
break;
}
page++;
}
console.log(`Found ${allCaches.length} caches in total.`);
const cachesByKey = allCaches.reduce((acc, cache) => {
const i = `${cache.ref}-${getType(cache.key)}`;
(acc[i] = acc[i] || []).push(cache);
return acc;
}, {});
let dryRun = false;
if (context.eventName === 'workflow_dispatch' && context.payload.inputs) {
dryRun = context.payload.inputs.dryrun === 'true';
}
for (const [key, caches] of Object.entries(cachesByKey)) {
caches.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
for (let i = 0; i < caches.length; i++) {
const cacheId = caches[i].id;
const key = caches[i].key;
const ref = caches[i].ref;
const branch = getBranchNameFromRef(ref);
if (i === 0) {
if (ref === 'refs/heads/main') continue;
if (await isBranchExists(branch)) {
continue;
} else {
console.log(`Branch ${branch} is no longer exists. deleting...`);
}
}
if (dryRun) {
console.log(`[Dry Run] Old cache for key "${key}" (ID: ${cacheId}) would be deleted.`);
} else {
console.log(`Deleting old cache for key "${key}" (ID: ${cacheId}).`);
await github.rest.actions.deleteActionsCacheById({
owner: context.repo.owner,
repo: context.repo.repo,
cache_id: cacheId,
});
}
}
}