-
Notifications
You must be signed in to change notification settings - Fork 0
97 lines (83 loc) · 3.24 KB
/
Copy pathcleanup-deployments.yml
File metadata and controls
97 lines (83 loc) · 3.24 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
name: Cleanup Old Deployments
on:
workflow_run:
workflows: ["Deploy to GitHub Pages"]
types: [completed]
schedule:
- cron: '15 3 * * *'
workflow_dispatch:
inputs:
keep_count:
description: Number of most recent deployments to keep
required: false
default: '2'
environment:
description: Deployment environment to clean
required: false
default: github-pages
permissions:
contents: read
deployments: write
jobs:
cleanup:
# On workflow_run, only proceed when deploy workflow succeeded.
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- name: Prune old deployment records
uses: actions/github-script@v7
with:
script: |
const keepInput = core.getInput('keep_count');
const envInput = core.getInput('environment');
const keepCount = Number(keepInput || '2');
const targetEnvironment = envInput || 'github-pages';
if (!Number.isFinite(keepCount) || keepCount < 1) {
core.setFailed(`Invalid keep_count: ${keepInput}`);
return;
}
const { owner, repo } = context.repo;
core.info(`Cleaning deployments for ${owner}/${repo} in environment "${targetEnvironment}"`);
core.info(`Keeping newest ${keepCount} deployment(s).`);
const deployments = await github.paginate(github.rest.repos.listDeployments, {
owner,
repo,
environment: targetEnvironment,
per_page: 100,
});
if (!deployments.length) {
core.info('No deployments found. Nothing to clean.');
return;
}
deployments.sort(
(a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
);
const toDelete = deployments.slice(keepCount);
core.info(`Found ${deployments.length} deployment(s). Deleting ${toDelete.length}.`);
for (const deployment of toDelete) {
core.info(`Processing deployment #${deployment.id} (${deployment.created_at})`);
// Mark inactive first; this improves deletion success for older records.
try {
await github.rest.repos.createDeploymentStatus({
owner,
repo,
deployment_id: deployment.id,
state: 'inactive',
description: 'Pruned by cleanup workflow',
auto_inactive: true,
});
} catch (err) {
core.warning(`Could not mark #${deployment.id} inactive: ${err.message}`);
}
try {
await github.rest.repos.deleteDeployment({
owner,
repo,
deployment_id: deployment.id,
});
core.info(`Deleted deployment #${deployment.id}`);
} catch (err) {
core.warning(`Could not delete deployment #${deployment.id}: ${err.message}`);
}
}
core.info('Deployment cleanup finished.');