Created
November 28, 2024 21:36
-
-
Save konstruktoid/60d1379c1ae6e8c7df606b7b43ebdf6c to your computer and use it in GitHub Desktop.
Download GitHub artifact
This file contains hidden or 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
#!/usr/bin/env python3 | |
# ruff: noqa: E501,PERF401 | |
# | |
"""Download the latest artifact from a GitHub repository.""" | |
import zipfile | |
from pathlib import Path | |
import requests | |
OWNER = "konstruktoid" | |
REPOSITORY = "ansible-role-hardening" | |
VALUE = "jsonl" | |
GITHUB_TOKEN = "" | |
FILE_NAME = f"artifact-{VALUE}" | |
ok_status_code = 200 | |
headers = { | |
"Accept": "application/vnd.github.v3+json", | |
"Authorization": f"Bearer {GITHUB_TOKEN}", | |
} | |
response = requests.get( | |
f"https://api.github.com/repos/{OWNER}/{REPOSITORY}/actions/artifacts", | |
timeout=5, | |
headers=headers, | |
) | |
ARTIFACT_ID = [] | |
for artifact in response.json()["artifacts"]: | |
if VALUE in artifact["name"]: | |
ARTIFACT_ID.append(artifact["id"]) | |
LATEST_ARTIFACT = max(ARTIFACT_ID) | |
response = requests.get( | |
f"https://api.github.com/repos/{OWNER}/{REPOSITORY}/actions/artifacts/{LATEST_ARTIFACT}", | |
timeout=5, | |
headers=headers, | |
) | |
with Path.open(f"{FILE_NAME}.reponse.json", "w", encoding="utf-8") as file: | |
file.write(response.text) | |
response = requests.get( | |
response.json()["archive_download_url"], | |
timeout=5, | |
headers=headers, | |
) | |
if response.status_code == ok_status_code: | |
with Path.open(f"{FILE_NAME}.zip", "wb") as file: | |
file.write(response.content) | |
with zipfile.ZipFile(f"{FILE_NAME}.zip", "r") as zip_ref: | |
zip_ref.extractall() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment