Track VERSION, compare it with Gitea tags via git ls-remote (API fallback), expose GET /api/update and a Services card with the current version.
This commit is contained in:
1 parent
eb8a9bb57b
commit
f1149974aa
15 files changed
+390
-2
No files matched your search
@@ -0,0 +1,182 @@
|
||||
"""Check the Gitea repository for newer tags (no auto-download).
|
||||
|
||||
python tools/check_updates.py
|
||||
python tools/check_updates.py --json
|
||||
python tools/check_updates.py --api https://gitea.example/api/v1/repos/owner/repo
|
||||
|
||||
The local version comes from the VERSION file. Only tags like ``v1.2.3`` or
|
||||
``1.2.3`` are compared; the check is read-only.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
stream.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
VERSION_FILE = os.path.join(BASE_DIR, "VERSION")
|
||||
DEFAULT_API = "https://gitea.strsv.ru/api/v1/repos/strsv/SteamBase"
|
||||
DEFAULT_WEB = "https://gitea.strsv.ru/strsv/SteamBase"
|
||||
DEFAULT_REMOTE = "origin"
|
||||
DEFAULT_TIMEOUT = 15
|
||||
CACHE_TTL = 3600
|
||||
VERSION_RE = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$")
|
||||
|
||||
_cache = {}
|
||||
|
||||
|
||||
def read_version(path=VERSION_FILE):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
value = handle.read().strip()
|
||||
except OSError:
|
||||
return "0.0.0"
|
||||
return value or "0.0.0"
|
||||
|
||||
|
||||
def parse_version(text):
|
||||
match = VERSION_RE.match((text or "").strip())
|
||||
if not match:
|
||||
return None
|
||||
return tuple(int(part) for part in match.groups())
|
||||
|
||||
|
||||
def fetch_tags_git(remote=DEFAULT_REMOTE, timeout=DEFAULT_TIMEOUT):
|
||||
"""Tags via the configured git remote (works for private repositories)."""
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["git", "ls-remote", "--tags", remote],
|
||||
cwd=BASE_DIR, capture_output=True, text=True, timeout=timeout,
|
||||
encoding="utf-8", errors="replace")
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise RuntimeError(f"git ls-remote failed: {type(exc).__name__}") from None
|
||||
if proc.returncode != 0:
|
||||
detail = (proc.stderr or "").strip()[:200] or str(proc.returncode)
|
||||
raise RuntimeError(f"git ls-remote failed: {detail}")
|
||||
tags = []
|
||||
for line in proc.stdout.splitlines():
|
||||
parts = line.split("\t")
|
||||
if len(parts) != 2 or not parts[1].startswith("refs/tags/"):
|
||||
continue
|
||||
name = parts[1][len("refs/tags/"):]
|
||||
if name.endswith("^{}"):
|
||||
continue
|
||||
if name not in tags:
|
||||
tags.append(name)
|
||||
return tags
|
||||
|
||||
|
||||
def fetch_tags_api(api_url, timeout=DEFAULT_TIMEOUT):
|
||||
url = api_url.rstrip("/") + "/tags?limit=50"
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "SteamBase/1.0"})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
data = json.load(response)
|
||||
except urllib.error.HTTPError as exc:
|
||||
raise RuntimeError(f"Gitea API HTTP {exc.code}") from None
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
|
||||
raise RuntimeError(f"Gitea API request failed: {type(exc).__name__}") from None
|
||||
if not isinstance(data, list):
|
||||
raise RuntimeError("unexpected Gitea API response")
|
||||
return [str(item.get("name") or "") for item in data if isinstance(item, dict)]
|
||||
|
||||
|
||||
def fetch_tags(api_url=DEFAULT_API, remote=DEFAULT_REMOTE,
|
||||
timeout=DEFAULT_TIMEOUT, method="auto"):
|
||||
"""Fetch tags via git (default) and fall back to the Gitea API."""
|
||||
if method in ("auto", "git"):
|
||||
try:
|
||||
return fetch_tags_git(remote, timeout)
|
||||
except RuntimeError:
|
||||
if method == "git":
|
||||
raise
|
||||
if method in ("auto", "api"):
|
||||
return fetch_tags_api(api_url, timeout)
|
||||
raise RuntimeError(f"unknown update method: {method}")
|
||||
|
||||
|
||||
def latest_version(tags):
|
||||
best = None
|
||||
best_name = None
|
||||
for tag in tags:
|
||||
parsed = parse_version(tag)
|
||||
if parsed and (best is None or parsed > best):
|
||||
best = parsed
|
||||
best_name = tag
|
||||
return best_name, best
|
||||
|
||||
|
||||
def check(api_url=DEFAULT_API, web_url=DEFAULT_WEB, current=None,
|
||||
remote=DEFAULT_REMOTE, method="auto",
|
||||
timeout=DEFAULT_TIMEOUT, ttl=CACHE_TTL):
|
||||
current = current or read_version()
|
||||
cache_key = (api_url, remote, method, current, timeout)
|
||||
now = time.time()
|
||||
cached = _cache.get(cache_key)
|
||||
if cached and now - cached[0] < ttl:
|
||||
return cached[1]
|
||||
tags = fetch_tags(api_url, remote, timeout, method)
|
||||
latest, latest_parsed = latest_version(tags)
|
||||
current_parsed = parse_version(current)
|
||||
update_available = bool(
|
||||
latest_parsed and current_parsed and latest_parsed > current_parsed)
|
||||
result = {
|
||||
"current": current,
|
||||
"latest": latest,
|
||||
"update_available": update_available,
|
||||
"url": f"{web_url.rstrip('/')}/src/tag/{latest}" if latest else None,
|
||||
"checked_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"tags": tags[:20],
|
||||
}
|
||||
_cache[cache_key] = (now, result)
|
||||
return result
|
||||
|
||||
|
||||
def clear_cache():
|
||||
_cache.clear()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Check Gitea tags for a newer version")
|
||||
ap.add_argument("--api", default=DEFAULT_API)
|
||||
ap.add_argument("--web", default=DEFAULT_WEB)
|
||||
ap.add_argument("--remote", default=DEFAULT_REMOTE)
|
||||
ap.add_argument("--method", choices=("auto", "git", "api"), default="auto")
|
||||
ap.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT)
|
||||
ap.add_argument("--json", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
try:
|
||||
result = check(api_url=args.api, web_url=args.web, remote=args.remote,
|
||||
method=args.method, timeout=args.timeout)
|
||||
except RuntimeError as exc:
|
||||
print(f"Update check failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
print(f"Current: {result['current']}")
|
||||
print(f"Latest: {result['latest'] or 'нет тегов'}")
|
||||
if result["update_available"]:
|
||||
print(f"Доступно обновление: {result['url']}")
|
||||
else:
|
||||
print("Обновлений нет")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user