Delete old artifacts #11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: 'Delete old artifacts' | |
on: | |
schedule: | |
- cron: '0 0 * * *' # Run daily at midnight | |
workflow_dispatch: | |
jobs: | |
delete-artifacts: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Delete old artifacts | |
uses: actions/github-script@v6 | |
with: | |
github-token: ${{ secrets.GITHUB_TOKEN }} | |
script: | | |
const { owner, repo } = context.repo; | |
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); | |
const artifacts = await github.paginate(github.rest.actions.listArtifactsForRepo, { | |
owner, | |
repo, | |
per_page: 100 | |
}); | |
const artifactMap = new Map(); | |
for (const artifact of artifacts) { | |
const createdAt = new Date(artifact.created_at); | |
if (createdAt > sevenDaysAgo) { | |
// Keep all artifacts less than 7 days old | |
continue; | |
} | |
if (!artifactMap.has(artifact.name) || createdAt > new Date(artifactMap.get(artifact.name).created_at)) { | |
artifactMap.set(artifact.name, artifact); | |
} | |
} | |
for (const artifact of artifacts) { | |
const createdAt = new Date(artifact.created_at); | |
if (createdAt > sevenDaysAgo) { | |
// Keep all artifacts less than 7 days old | |
continue; | |
} | |
if (artifact.id !== artifactMap.get(artifact.name)?.id) { | |
console.log(`Deleting artifact ${artifact.name} with ID ${artifact.id}`); | |
await github.rest.actions.deleteArtifact({ | |
owner, | |
repo, | |
artifact_id: artifact.id | |
}); | |
} | |
} |