This commit is contained in:
NianBroken
2024-07-17 19:48:01 +08:00 Unverified
parent 1d1b19e17f
commit bc9486f8d9
+28 -21
View File
@@ -30,28 +30,35 @@ class GitHubActionsManager:
self.log(f"Failed to delete run with ID {run_id}. Status code: {response.status_code}") # 打印错误信息 self.log(f"Failed to delete run with ID {run_id}. Status code: {response.status_code}") # 打印错误信息
def delete_old_runs(self): def delete_old_runs(self):
next_page = self.runs_url # 初始化下一页的URL为第一页 while True: # 无限循环,直到没有符合条件的运行记录为止
page_number = 1 # 初始化页数计数器 next_page = self.runs_url # 初始化下一页的URL为第一
while next_page: # 循环直到没有下一页 page_number = 1 # 初始化页数计数器
self.log(f"Fetching page {page_number}") # 输出当前的页数 any_deleted = False # 标记是否有记录被删除
# 发送GET请求获取一页工作流运行记录
response = requests.get(next_page, headers={"Authorization": f"token {self.token}"})
if response.status_code == 200: # 如果请求成功
data = response.json() # 将响应数据转换为JSON格式
runs = data["workflow_runs"] # 获取运行记录列表
next_page = response.links.get("next", {}).get("url") # 获取下一页的URL
page_number += 1 # 增加页数计数器
for run in runs: # 遍历每条运行记录 while next_page: # 循环直到没有下一页
# 将运行记录的创建时间转换为UTC时间 self.log(f"Fetching page {page_number}") # 输出当前的页数
run_time = datetime.strptime(run["created_at"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) # 发送GET请求获取一页工作流运行记录
# 计算当前时间与运行记录创建时间的差值 response = requests.get(next_page, headers={"Authorization": f"token {self.token}"})
time_difference = self.current_time - run_time if response.status_code == 200: # 如果请求成功
if time_difference > timedelta(hours=hour_count): # 如果差值超过指定小时 默认168小时 data = response.json() # 将响应数据转换为JSON格式
self.delete_run(run["id"]) # 删除运行记录 runs = data["workflow_runs"] # 获取运行记录列表
else: # 如果请求失败 next_page = response.links.get("next", {}).get("url") # 获取下一页的URL
self.log(f"Failed to fetch runs. Status code: {response.status_code}") # 打印错误信息 page_number += 1 # 增加页数计数器
break # 退出循环
for run in runs: # 遍历每条运行记录
# 将运行记录的创建时间转换为UTC时间
run_time = datetime.strptime(run["created_at"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
# 计算当前时间与运行记录创建时间的差值
time_difference = self.current_time - run_time
if time_difference > timedelta(hours=hour_count): # 如果差值超过指定小时 默认168小时
self.delete_run(run["id"]) # 删除运行记录
any_deleted = True # 标记有记录被删除
else: # 如果请求失败
self.log(f"Failed to fetch runs. Status code: {response.status_code}") # 打印错误信息
break # 退出循环
if not any_deleted: # 如果没有任何记录被删除,退出循环
break
def log(self, message): def log(self, message):
current_time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S:%f")[:-3] # 获取当前时间,精确到三位毫秒 current_time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S:%f")[:-3] # 获取当前时间,精确到三位毫秒