From f6624a96452463b19df0f8e96582393d927a610a Mon Sep 17 00:00:00 2001 From: Sander Devisscher Date: Mon, 13 Jan 2025 13:28:34 +0100 Subject: [PATCH] Create delete_old_artifacts.yaml #316 --- .github/workflows/delete_old_artifacts.yaml | 54 +++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 .github/workflows/delete_old_artifacts.yaml diff --git a/.github/workflows/delete_old_artifacts.yaml b/.github/workflows/delete_old_artifacts.yaml new file mode 100644 index 00000000..c70643a8 --- /dev/null +++ b/.github/workflows/delete_old_artifacts.yaml @@ -0,0 +1,54 @@ +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 + }); + } + }