Files
lnxgit/tools/clean_release.py
LnxGit 77dc9e917f 把这轮用到的三个运维脚本固化进仓库
* scripts/wsl_upload_release.sh —— 内网直传 APK 到 Release(单次整文件)
* tools/clean_release.py        —— 清理 Release 里堆积的附件
* scripts/wsl_share_packages.sh —— 跨架构复用已下载的依赖源码包

这些都是这轮踩坑后总结出来的可复用做法:Cloudflare 的 100 MB 限制、
附件操作需要的管理员令牌、以及新建架构时依赖下载超时。
2026-09-23 03:44:59 +08:00

92 lines
3.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""清理 Gitea Release 里堆积的附件。
历史上用切片上传大 APK 时,Release 里堆了几十个 ``xxx.apk.part001`` 这样的
同名附件,还有若干测试用的 ``probe_*.bin``。这个脚本一次性清干净。
走**内网直连**(默认 192.168.100.103:8080)而不是公网域名:
公网经 Cloudflare,附件操作没必要绕那一层。
令牌需要**仓库管理员**权限 —— 只读令牌删除会返回 403。
用法::
python tools/clean_release.py --token <token> [--dry-run]
"""
from __future__ import annotations
import argparse
import json
import urllib.error
import urllib.request
DEFAULT_BASE = "http://192.168.100.103:8080"
DEFAULT_REPO = "l/lnxgit"
DEFAULT_RELEASE_ID = 1
def api(base: str, token: str, path: str, method: str = "GET"):
request = urllib.request.Request(f"{base}/api/v1/{path}", method=method)
request.add_header("Authorization", f"token {token}")
request.add_header("Accept", "application/json")
with urllib.request.urlopen(request, timeout=60) as response:
body = response.read()
return json.loads(body) if body else None
def main() -> int:
parser = argparse.ArgumentParser(description="清理 Release 附件")
parser.add_argument("--token", required=True)
parser.add_argument("--base", default=DEFAULT_BASE)
parser.add_argument("--repo", default=DEFAULT_REPO)
parser.add_argument("--release-id", type=int, default=DEFAULT_RELEASE_ID)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--keep", action="append", default=[],
help="保留匹配该名字的附件(可多次,支持前缀匹配)")
args = parser.parse_args()
release = api(args.base, args.token,
f"repos/{args.repo}/releases/{args.release_id}")
assets = release.get("assets", [])
print(f"Release id={release['id']} tag={release['tag_name']}")
print(f"现有附件 {len(assets)} 个,合计 "
f"{sum(a['size'] for a in assets) / 1048576:.1f} MB\n")
targets = [a for a in assets
if not any(a["name"].startswith(k) for k in args.keep)]
if not targets:
print("没有需要清理的附件")
return 0
deleted = failed = 0
for asset in targets:
name = asset["name"]
if args.dry_run:
print(f" [dry-run] 将删除 {name}({asset['size'] / 1048576:.1f} MB)")
continue
try:
api(args.base, args.token,
f"repos/{args.repo}/releases/{args.release_id}/assets/{asset['id']}",
method="DELETE")
deleted += 1
print(f" 已删除 {name}")
except urllib.error.HTTPError as exc:
failed += 1
hint = "(令牌可能没有管理员权限)" if exc.code == 403 else ""
print(f" 删除失败 {name}: HTTP {exc.code} {exc.reason}{hint}")
except Exception as exc: # noqa: BLE001
failed += 1
print(f" 删除失败 {name}: {type(exc).__name__}: {exc}")
if not args.dry_run:
print(f"\n==> 已删除 {deleted} 个,失败 {failed} 个")
remaining = api(args.base, args.token,
f"repos/{args.repo}/releases/{args.release_id}").get("assets", [])
print(f" 剩余附件 {len(remaining)} 个")
return 0 if failed == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())