diff --git a/.forgejo/workflows/cleanup.yml b/.forgejo/workflows/cleanup.yml new file mode 100644 index 0000000..a8de85f --- /dev/null +++ b/.forgejo/workflows/cleanup.yml @@ -0,0 +1,58 @@ +on: + workflow_dispatch: + schedule: + - cron: "30 3 * * *" + +jobs: + cleanup-workflow-runs: + runs-on: docker + steps: + - name: Install Packages + run: apt-get update && apt-get install -y curl jq + + - name: Delete workflow runs older than 14 days + env: + TOKEN: ${{ forgejo.token }} + API: ${{ forgejo.api_url }} + REPO: ${{ forgejo.repository }} + CURRENT_RUN_ID: ${{ forgejo.run_id }} + run: | + set -eu + + CUTOFF="$(date -u -d "14 days ago" +"%Y-%m-%dT%H:%M:%SZ")" + PAGE=1 + DELETE_IDS=delete-workflow-runs.txt + + : > "$DELETE_IDS" + + while :; do + curl -fsS \ + -H "Authorization: token $TOKEN" \ + "$API/repos/$REPO/actions/runs?page=$PAGE&limit=50" \ + -o runs.json + + COUNT="$(jq 'if type == "array" then length else (.workflow_runs // []) | length end' runs.json)" + test "$COUNT" -gt 0 || break + + jq -r \ + --arg cutoff "$CUTOFF" \ + --arg current "$CURRENT_RUN_ID" \ + 'if type == "array" then . else (.workflow_runs // []) end + | .[] + | select(type == "object") + | select((.id | tostring) != $current) + | select((.status // .conclusion) as $status | ["success", "failure", "cancelled", "skipped", "succeeded", "failed"] | index($status)) + | select((.created // .created_at) < $cutoff) + | .id' runs.json \ + >> "$DELETE_IDS" + + PAGE="$((PAGE + 1))" + done + + while IFS= read -r run_id; do + test -n "$run_id" || continue + echo "Deleting workflow run $run_id" + curl -fsS -X DELETE \ + -H "Authorization: token $TOKEN" \ + "$API/repos/$REPO/actions/runs/$run_id" + done < "$DELETE_IDS"