Lawnmower/defs/ci.py

78 lines
2.8 KiB
Python
Raw Permalink Normal View History

2022-04-27 08:08:33 +00:00
import datetime
2022-04-27 09:08:14 +00:00
from configparser import RawConfigParser
2022-04-27 08:08:33 +00:00
from os.path import exists
2022-04-27 09:08:14 +00:00
from os import remove, sep
2022-04-27 08:08:33 +00:00
from typing import Optional
2022-04-27 09:08:14 +00:00
from httpx import get, AsyncClient
2022-04-27 08:08:33 +00:00
2022-04-27 09:08:14 +00:00
""" Init httpx client """
# 使用自定义 UA
config = RawConfigParser()
config.read("config.ini")
ghp: str = ""
ghp = config.get("basic", "ghp", fallback=ghp)
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
"Authorization": f"token {ghp}",
}
client = AsyncClient(timeout=10.0, headers=headers, follow_redirects=True)
2022-04-27 08:08:33 +00:00
class Artifact:
def __init__(self, data: dict):
self.id: int = data.get("id", 0)
self.name: str = "Grasscutter.zip"
self.url: str = data.get("archive_download_url", "")
size: int = data.get("archive_size", 0)
self.size: str = f"{size / 1024 / 1024:.2f} MB"
self.expired: bool = data.get("expired", False)
created_at: str = data.get("created_at", "")
# 2022-04-27T06:31:46Z
try:
self.created_at: datetime.datetime = datetime.datetime.strptime(
created_at, "%Y-%m-%dT%H:%M:%SZ"
) + datetime.timedelta(hours=8)
except ValueError:
self.created_at: datetime.datetime = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
self.created_time: str = self.created_at.strftime("%Y-%m-%d %H:%M:%S")
self.hash: str = get_hash()
2022-04-27 09:08:14 +00:00
async def download(self, path: str = f"data{sep}Grasscutter.zip"):
if exists(path):
remove(path)
content = await client.get(self.url)
if content.status_code == 404:
raise FileNotFoundError
content = content.content
with open(path, 'wb') as f:
f.write(content)
2022-04-27 08:08:33 +00:00
async def get_artifact() -> Optional[Artifact]:
2022-04-27 09:08:14 +00:00
req = await client.get("https://api.github.com/repos/Grasscutters/Grasscutter/actions/artifacts?per_page=1")
2022-04-27 08:08:33 +00:00
if req.status_code == 200:
data = req.json()
if data.get("artifacts", []):
return Artifact(data["artifacts"][0])
return None
2022-05-30 13:24:53 +00:00
def format_branch(branch: str) -> str:
for i in ["-", ".", " ", ":"]:
branch = branch.replace(i, "_")
return branch
2022-04-27 08:08:33 +00:00
def get_hash() -> str:
req = get("https://api.github.com/repos/Grasscutters/Grasscutter/actions/runs?per_page=1&status=success")
if req.status_code == 200:
data = req.json()
if data.get("workflow_runs", []):
2022-05-30 13:24:53 +00:00
branch = data["workflow_runs"][0]["head_branch"]
hash_str = data["workflow_runs"][0]["head_commit"]["id"][:7]
message = data["workflow_runs"][0]["head_commit"]["message"][:200]
return f"#{format_branch(branch)} #{hash_str} \n\n" \
f"{message}"
2022-04-27 09:08:14 +00:00
return "Unknown."