78 lines
2.8 KiB
Python
78 lines
2.8 KiB
Python
|
|
#!/usr/bin/env python
|
||
|
|
import os
|
||
|
|
import yaml
|
||
|
|
import subprocess
|
||
|
|
import sys
|
||
|
|
|
||
|
|
def download_file(url):
|
||
|
|
"""使用 curl 下载文件内容"""
|
||
|
|
result = subprocess.run(["curl", "-s", url], capture_output=True, text=True)
|
||
|
|
if result.returncode != 0:
|
||
|
|
print(f"下载 {url} 时出错,跳过。")
|
||
|
|
return None
|
||
|
|
return result.stdout
|
||
|
|
|
||
|
|
def main():
|
||
|
|
# 读取 list.yaml
|
||
|
|
try:
|
||
|
|
with open("list.yaml", "r", encoding="utf-8") as f:
|
||
|
|
items = yaml.safe_load(f)
|
||
|
|
except FileNotFoundError:
|
||
|
|
print("list.yaml 文件不存在。")
|
||
|
|
sys.exit(0)
|
||
|
|
|
||
|
|
modified = False
|
||
|
|
|
||
|
|
for item in items:
|
||
|
|
file_path = item.get("file")
|
||
|
|
source = item.get("source")
|
||
|
|
if not file_path or not source:
|
||
|
|
print("条目缺少 file 或 source 字段,跳过。")
|
||
|
|
continue
|
||
|
|
|
||
|
|
print(f"处理 {file_path} 从 {source}")
|
||
|
|
new_content = download_file(source)
|
||
|
|
if new_content is None:
|
||
|
|
# 如果下载失败,继续处理下一个文件
|
||
|
|
continue
|
||
|
|
|
||
|
|
# 去掉前导斜杠(如果希望相对于仓库根目录存放,也可以自行调整目录结构)
|
||
|
|
rel_path = file_path.lstrip("/")
|
||
|
|
# 创建必要目录
|
||
|
|
os.makedirs(os.path.dirname(rel_path), exist_ok=True)
|
||
|
|
|
||
|
|
# 如果文件存在,检查内容是否已更新
|
||
|
|
if os.path.exists(rel_path):
|
||
|
|
with open(rel_path, "r", encoding="utf-8") as f:
|
||
|
|
old_content = f.read()
|
||
|
|
if old_content == new_content:
|
||
|
|
print(f"{rel_path} 内容未改变。")
|
||
|
|
continue
|
||
|
|
|
||
|
|
with open(rel_path, "w", encoding="utf-8") as f:
|
||
|
|
f.write(new_content)
|
||
|
|
print(f"更新了 {rel_path}")
|
||
|
|
modified = True
|
||
|
|
|
||
|
|
# 如果有修改则提交到仓库
|
||
|
|
if modified:
|
||
|
|
# 配置 git 用户信息
|
||
|
|
subprocess.run(["git", "config", "--global", "user.email", "cicd@sugarscat.cn"], check=True)
|
||
|
|
subprocess.run(["git", "config", "--global", "user.name", "CI/CD"], check=True)
|
||
|
|
|
||
|
|
repo_url = os.environ.get("THE_REPO")
|
||
|
|
# 将 https:// 替换为 https://oauth2:token@ 形式
|
||
|
|
token = os.environ.get("REPO_TOKEN")
|
||
|
|
new_repo_url = repo_url.replace("https://", f"https://oauth2:{token}@")
|
||
|
|
subprocess.run(["git", "remote", "set-url", "origin", new_repo_url], check=True)
|
||
|
|
subprocess.run(["git", "add", "."], check=True)
|
||
|
|
commit_message = "自动更新:从 list.yaml 下载最新文件"
|
||
|
|
# 如果没有变更,则 git commit 会返回非零状态,可用 || true 处理
|
||
|
|
subprocess.run(["git", "commit", "-m", commit_message], check=False)
|
||
|
|
subprocess.run(["git", "push", "origin", "HEAD"], check=True)
|
||
|
|
else:
|
||
|
|
print("没有需要更新的文件。")
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
main()
|