Last active
December 15, 2022 10:49
-
-
Save NejcZupec/3b8a91e6c5305659b072e99c2da6da9e to your computer and use it in GitHub Desktop.
Cleanup GitHub Actions artifacts
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
# Requirements: Python 3.9+ | |
# pip install PyGithub | |
# Get token here https://github.com/settings/tokens/new (need all repo permissions) | |
# Run the script: TOKEN='<token>' REPOSITORY=<org>/<repo> python cleanerV2.py <start_page> | |
import time | |
import sys | |
import datetime | |
import os | |
from github import Github | |
from github.GithubException import RateLimitExceededException | |
TOKEN = os.environ.get("TOKEN") | |
REPOSITORY = os.environ.get("REPOSITORY") | |
CUTOFF_DATE = datetime.datetime.now() - datetime.timedelta(days=7) # 1 week ago | |
CUTOFF_SIZE = 1 # 1 B | |
def _delete_artifacts(): | |
start_page = int(sys.argv[1]) if len(sys.argv) > 1 else 0 | |
g = Github( | |
login_or_token=TOKEN, | |
per_page=100, | |
) | |
candidates_to_delete = 0 | |
candidates_size = 0 | |
keep_size = 0 | |
try: | |
repo = g.get_repo(REPOSITORY) | |
repo.get_artifacts() | |
artifacts_response = repo.get_artifacts() | |
current_page = start_page | |
for i in range(1000): | |
print("CURRENT PAGE:", current_page, "RATE LIMIT", g.rate_limiting, " --------------------------------") | |
print("CANDIDATES COUNT:", candidates_to_delete, "CANDIDATE SIZE", candidates_size, "KEEP SIZE", keep_size) | |
artifacts = artifacts_response.get_page(current_page) | |
if len(artifacts) == 0: | |
print("No artifacts found, aborting") | |
exit(0) | |
for artifact in artifacts: | |
to_be_deleted = artifact.created_at < CUTOFF_DATE and artifact.size_in_bytes > CUTOFF_SIZE | |
print(artifact.created_at, artifact.name, artifact.expires_at, artifact.size_in_bytes, to_be_deleted) | |
if to_be_deleted: | |
candidates_size += artifact.size_in_bytes | |
candidates_to_delete += 1 | |
artifact.delete() | |
else: | |
keep_size += artifact.size_in_bytes | |
current_page += 1 | |
except RateLimitExceededException: | |
reset_time = datetime.datetime.fromtimestamp(g.rate_limiting_resettime) | |
delta = reset_time - datetime.datetime.now() | |
print("Rate limit exceeded, reset in:", delta.seconds, "seconds") | |
time.sleep(60) | |
_delete_artifacts() | |
if __name__ == "__main__": | |
_delete_artifacts() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment