371 lines
12 KiB
Python
371 lines
12 KiB
Python
"""Offline-friendly update checks and safe fast-forward installation."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import time
|
|
import tomllib
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
|
|
from . import __version__
|
|
from .utils import atomic_write_json
|
|
|
|
DEFAULT_REPO_URL = "https://git.bipfr.ru/KoDer/AiRouter.git"
|
|
UPDATE_CACHE = Path.home() / ".cache" / "airouter" / "update.json"
|
|
UPDATE_TTL = 6 * 60 * 60
|
|
CACHE_TTL = UPDATE_TTL
|
|
CACHE_PATH = UPDATE_CACHE
|
|
REPO_ROOT = Path(__file__).resolve().parents[1]
|
|
_VERSION_RE = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)$")
|
|
|
|
|
|
@dataclass
|
|
class UpdateInfo:
|
|
current: str
|
|
latest: str
|
|
available: bool
|
|
url: str
|
|
checked_at: float
|
|
error: str = ""
|
|
|
|
|
|
@dataclass
|
|
class UpdateResult:
|
|
updated: bool
|
|
version: str
|
|
restart_required: bool
|
|
message: str
|
|
|
|
|
|
def parse_version(value: str) -> tuple[int, int, int] | None:
|
|
"""Parse ``vMAJOR.MINOR.PATCH`` (or an unprefixed equivalent)."""
|
|
|
|
if not isinstance(value, str):
|
|
return None
|
|
match = _VERSION_RE.fullmatch(value.strip())
|
|
if not match:
|
|
return None
|
|
return tuple(int(part) for part in match.groups())
|
|
|
|
|
|
def _git_env() -> dict[str, str]:
|
|
env = os.environ.copy()
|
|
for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"):
|
|
env.pop(key, None)
|
|
env.update(
|
|
{
|
|
"GIT_CONFIG_GLOBAL": os.devnull,
|
|
"GIT_CONFIG_NOSYSTEM": "1",
|
|
"GIT_TERMINAL_PROMPT": "0",
|
|
"GCM_INTERACTIVE": "Never",
|
|
"LC_ALL": "C",
|
|
}
|
|
)
|
|
return env
|
|
|
|
|
|
def _run(
|
|
command: list[str], *, cwd: Path | None = None, timeout: float = 60
|
|
) -> subprocess.CompletedProcess[str] | None:
|
|
try:
|
|
return subprocess.run(
|
|
command,
|
|
cwd=str(cwd) if cwd is not None else None,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL,
|
|
text=True,
|
|
timeout=max(0.1, float(timeout)),
|
|
env=_git_env(),
|
|
check=False,
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired, ValueError):
|
|
return None
|
|
|
|
|
|
def _public_repo_url(repo_url: str) -> str:
|
|
"""Remove URL credentials and fragments before displaying/caching a URL."""
|
|
|
|
value = str(repo_url or "").strip()
|
|
scp_match = re.fullmatch(r"[^/@\s]+@([^:\s]+):(.+)", value)
|
|
if scp_match:
|
|
value = f"https://{scp_match.group(1)}/{scp_match.group(2)}"
|
|
try:
|
|
parsed = urlsplit(value)
|
|
if parsed.scheme in {"http", "https"} and parsed.hostname:
|
|
host = parsed.hostname
|
|
if ":" in host:
|
|
host = f"[{host}]"
|
|
if parsed.port:
|
|
host += f":{parsed.port}"
|
|
return urlunsplit((parsed.scheme, host, parsed.path, "", ""))
|
|
except ValueError:
|
|
pass
|
|
# Local paths are useful in tests and private installs. Query/fragment
|
|
# syntax has no meaning for them and is omitted.
|
|
return value.split("#", 1)[0].split("?", 1)[0]
|
|
|
|
|
|
def _repo_key(repo_url: str) -> str:
|
|
return _public_repo_url(repo_url).removesuffix(".git").rstrip("/")
|
|
|
|
|
|
def _tag_url(repo_url: str, tag: str) -> str:
|
|
public = _public_repo_url(repo_url).removesuffix(".git").rstrip("/")
|
|
try:
|
|
parsed = urlsplit(public)
|
|
host = (parsed.hostname or "").lower()
|
|
except ValueError:
|
|
host = ""
|
|
if host == "github.com" or host.endswith(".github.com"):
|
|
return f"{public}/releases/tag/{tag}"
|
|
if host:
|
|
return f"{public}/-/tags/{tag}"
|
|
return f"{public}/tags/{tag}"
|
|
|
|
|
|
def _read_cache(repo_key: str, current: str) -> UpdateInfo | None:
|
|
try:
|
|
import json
|
|
|
|
raw = json.loads(Path(UPDATE_CACHE).read_text(encoding="utf-8"))
|
|
except (OSError, ValueError, TypeError):
|
|
return None
|
|
if not isinstance(raw, dict):
|
|
return None
|
|
if raw.get("repo_url") != repo_key or raw.get("current") != current:
|
|
return None
|
|
checked_at = raw.get("checked_at")
|
|
latest = raw.get("latest")
|
|
if not isinstance(checked_at, (int, float)) or not isinstance(latest, str):
|
|
return None
|
|
age = time.time() - float(checked_at)
|
|
if age < 0 or age >= UPDATE_TTL or raw.get("error"):
|
|
return None
|
|
current_version = parse_version(current)
|
|
latest_version = parse_version(latest)
|
|
if current_version is None or latest_version is None:
|
|
return None
|
|
return UpdateInfo(
|
|
current=current,
|
|
latest=latest,
|
|
available=latest_version > current_version,
|
|
url=str(raw.get("url") or _public_repo_url(repo_key)),
|
|
checked_at=float(checked_at),
|
|
)
|
|
|
|
|
|
def _write_cache(info: UpdateInfo, repo_key: str) -> None:
|
|
try:
|
|
atomic_write_json(
|
|
Path(UPDATE_CACHE),
|
|
{
|
|
"repo_url": repo_key,
|
|
"current": info.current,
|
|
"latest": info.latest,
|
|
"url": info.url,
|
|
"checked_at": info.checked_at,
|
|
"error": "",
|
|
},
|
|
)
|
|
except (OSError, ValueError, TypeError):
|
|
pass
|
|
|
|
|
|
def _latest_tag(output: str) -> str | None:
|
|
best: tuple[tuple[int, int, int], str] | None = None
|
|
for line in output.splitlines():
|
|
parts = line.split(None, 1)
|
|
if len(parts) != 2:
|
|
continue
|
|
ref = parts[1].strip()
|
|
if not ref.startswith("refs/tags/") or ref.endswith("^{}"):
|
|
continue
|
|
tag = ref[len("refs/tags/") :]
|
|
version = parse_version(tag)
|
|
if version is None:
|
|
continue
|
|
if best is None or version > best[0]:
|
|
best = (version, tag)
|
|
return best[1] if best else None
|
|
|
|
|
|
def check_for_updates(
|
|
force: bool = False,
|
|
timeout: float = 8,
|
|
repo_url: str = DEFAULT_REPO_URL,
|
|
) -> UpdateInfo:
|
|
"""Check remote Git tags, caching successful checks for six hours."""
|
|
|
|
current = str(__version__)
|
|
current_version = parse_version(current)
|
|
repo_key = _repo_key(repo_url)
|
|
if current_version is None:
|
|
return UpdateInfo(
|
|
current=current,
|
|
latest=current,
|
|
available=False,
|
|
url=_public_repo_url(repo_url),
|
|
checked_at=time.time(),
|
|
error="Invalid current version",
|
|
)
|
|
if not force:
|
|
cached = _read_cache(repo_key, current)
|
|
if cached is not None:
|
|
return cached
|
|
|
|
result = _run(
|
|
["git", "ls-remote", "--tags", "--", str(repo_url)],
|
|
timeout=timeout,
|
|
)
|
|
if result is None:
|
|
return UpdateInfo(
|
|
current=current,
|
|
latest=current,
|
|
available=False,
|
|
url=_public_repo_url(repo_url),
|
|
checked_at=time.time(),
|
|
error="Update check failed or timed out",
|
|
)
|
|
if result.returncode != 0:
|
|
return UpdateInfo(
|
|
current=current,
|
|
latest=current,
|
|
available=False,
|
|
url=_public_repo_url(repo_url),
|
|
checked_at=time.time(),
|
|
error="Update check failed",
|
|
)
|
|
latest = _latest_tag(result.stdout or "")
|
|
if latest is None:
|
|
return UpdateInfo(
|
|
current=current,
|
|
latest=current,
|
|
available=False,
|
|
url=_public_repo_url(repo_url),
|
|
checked_at=time.time(),
|
|
error="No version tags found",
|
|
)
|
|
latest_version = parse_version(latest)
|
|
assert latest_version is not None
|
|
info = UpdateInfo(
|
|
current=current,
|
|
latest=latest,
|
|
available=latest_version > current_version,
|
|
url=_tag_url(repo_url, latest),
|
|
checked_at=time.time(),
|
|
)
|
|
_write_cache(info, repo_key)
|
|
return info
|
|
|
|
|
|
def _project_version(repo: Path) -> str:
|
|
try:
|
|
with (repo / "pyproject.toml").open("rb") as handle:
|
|
data = tomllib.load(handle)
|
|
value = data.get("project", {}).get("version")
|
|
return str(value) if value else str(__version__)
|
|
except (OSError, ValueError, TypeError):
|
|
return str(__version__)
|
|
|
|
|
|
def _refuse(message: str) -> UpdateResult:
|
|
return UpdateResult(
|
|
updated=False,
|
|
version=str(__version__),
|
|
restart_required=False,
|
|
message=message,
|
|
)
|
|
|
|
|
|
def install_update(*, repo_url: str = DEFAULT_REPO_URL) -> UpdateResult:
|
|
"""Fast-forward a clean Git checkout and optionally refresh its venv.
|
|
|
|
The function never stashes, resets, checks out over, or discards user work.
|
|
"""
|
|
|
|
repo = Path(REPO_ROOT).expanduser().resolve()
|
|
root_result = _run(["git", "rev-parse", "--show-toplevel"], cwd=repo)
|
|
if root_result is None or root_result.returncode != 0:
|
|
return _refuse("AiRouter is not running from a Git checkout.")
|
|
try:
|
|
if Path((root_result.stdout or "").strip()).resolve() != repo:
|
|
return _refuse("AiRouter source root is not a Git checkout.")
|
|
except OSError:
|
|
return _refuse("AiRouter source root is not accessible.")
|
|
|
|
before = _run(["git", "rev-parse", "HEAD"], cwd=repo)
|
|
if before is None or before.returncode != 0:
|
|
return _refuse("Unable to inspect the Git checkout.")
|
|
head_before = (before.stdout or "").strip()
|
|
|
|
status = _run(
|
|
["git", "status", "--porcelain=v1", "--untracked-files=all"], cwd=repo
|
|
)
|
|
if status is None or status.returncode != 0:
|
|
return _refuse("Unable to verify that the working tree is clean.")
|
|
if (status.stdout or "").strip():
|
|
return _refuse("Working tree is not clean; refusing to update.")
|
|
|
|
fetched = _run(
|
|
["git", "fetch", "--tags", "--prune", "--", str(repo_url)],
|
|
cwd=repo,
|
|
timeout=120,
|
|
)
|
|
if fetched is None or fetched.returncode != 0:
|
|
return _refuse("Unable to fetch updates.")
|
|
|
|
ancestor = _run(["git", "merge-base", "--is-ancestor", "HEAD", "FETCH_HEAD"], cwd=repo)
|
|
if ancestor is None:
|
|
return _refuse("Unable to verify fast-forward history.")
|
|
if ancestor.returncode == 1:
|
|
return _refuse("Remote history is not fast-forward; refusing to merge.")
|
|
if ancestor.returncode != 0:
|
|
return _refuse("Unable to verify fast-forward history.")
|
|
|
|
# Re-check immediately before merging in case another process changed files
|
|
# while the fetch was running. ``--ff-only`` remains the final safeguard.
|
|
status = _run(
|
|
["git", "status", "--porcelain=v1", "--untracked-files=all"], cwd=repo
|
|
)
|
|
if status is None or status.returncode != 0 or (status.stdout or "").strip():
|
|
return _refuse("Working tree changed during update; refusing to merge.")
|
|
|
|
merged = _run(["git", "merge", "--ff-only", "FETCH_HEAD"], cwd=repo)
|
|
if merged is None or merged.returncode != 0:
|
|
return _refuse("Fast-forward merge failed; no changes were discarded.")
|
|
|
|
after = _run(["git", "rev-parse", "HEAD"], cwd=repo)
|
|
if after is None or after.returncode != 0:
|
|
return _refuse("Update completed but the new revision could not be verified.")
|
|
head_after = (after.stdout or "").strip()
|
|
if head_after == head_before:
|
|
return UpdateResult(
|
|
updated=False,
|
|
version=_project_version(repo),
|
|
restart_required=False,
|
|
message="AiRouter is already up to date.",
|
|
)
|
|
|
|
version = _project_version(repo)
|
|
pip = repo / ".venv" / "bin" / "pip"
|
|
if pip.is_file():
|
|
installed = _run([str(pip), "install", "-e", "."], cwd=repo, timeout=300)
|
|
if installed is None or installed.returncode != 0:
|
|
return UpdateResult(
|
|
updated=True,
|
|
version=version,
|
|
restart_required=True,
|
|
message=f"Source updated to {version}, but dependency installation failed; restart AiRouter.",
|
|
)
|
|
return UpdateResult(
|
|
updated=True,
|
|
version=version,
|
|
restart_required=True,
|
|
message=f"Updated to {version}; restart AiRouter to use the new version.",
|
|
)
|