Files
lintunes/lintunes/updater.py
T
trav f21c31940f
macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
v0.97.0: macOS port (Round 129): OS-aware paths, config and cookies; Mac now-playing, packaging (PyInstaller .app, dmg build, signing notes, CI workflow) and docs
2026-11-17 22:41:48 -08:00

188 lines
7.5 KiB
Python

"""Self-update via git.
LinTunes runs straight from its git checkout (editable install), so an update
is just a fast-forward `git pull` followed by an app relaunch. The Updater
periodically fetches the checkout's upstream and reports how many commits
behind we are; `update_async()` applies them with `--ff-only` (never a merge,
never a conflicted tree). Network git calls run on daemon threads — same
pattern as lastfm.py — and report back through Qt signals.
When the package isn't running from a git checkout (or has no upstream), the
updater disables itself silently and the version display is just a label.
The built Mac app (``paths.FROZEN``) has no checkout, and must never run
git at all — on a Mac without the developer tools, ``/usr/bin/git`` pops
an "install the command line tools" dialog. So it asks GitHub's Releases
API instead (``release_info``) and emits ``release_available``; the version
button opens that release's page. Nothing is downloaded or replaced. With
``release_info.GITHUB_REPO`` empty the app never checks.
"""
import logging
import subprocess
import threading
from pathlib import Path
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
from lintunes import __version__, paths, release_info
log = logging.getLogger(__name__)
FIRST_CHECK_MS = 10 * 1000 # shortly after launch, off the startup path
RECHECK_INTERVAL_MS = 4 * 3600 * 1000 # then every 4 hours
class Updater(QObject):
update_available = pyqtSignal(int) # commits behind upstream
update_applied = pyqtSignal() # pull succeeded; caller restarts the app
update_failed = pyqtSignal(str)
# The frozen app's path: (newer version, its release page)
release_available = pyqtSignal(str, str)
def __init__(self, parent=None, release_mode: bool | None = None):
super().__init__(parent)
self._root = str(Path(__file__).resolve().parents[1])
self._busy = False
self._timer = None
self._enabled = None # probed lazily — see enabled
# Releases instead of git: the built app, never a checkout.
self.release_mode = (paths.FROZEN if release_mode is None
else release_mode)
@property
def enabled(self) -> bool:
"""Whether this checkout is a git repo with an upstream.
Probed on first use rather than in __init__: the two `git rev-parse`
calls have a 15 s timeout each, and running them during startup put
that stall on the main thread before the window was up. First use is
now `_check`, on a background thread.
"""
if self.release_mode:
return release_info.latest_release_url() is not None
if self._enabled is None:
self._enabled = (
self._git("rev-parse", "--show-toplevel") is not None
and self._git("rev-parse", "--abbrev-ref", "@{upstream}")
is not None)
return self._enabled
def short_hash(self) -> str | None:
"""The checkout's current commit, for telling builds apart."""
if self.release_mode:
return None
return self._git("rev-parse", "--short", "HEAD")
def start_checking(self):
"""First check shortly after launch, then every few hours."""
if self.release_mode and not self.enabled:
return # no release repo named: the app never checks
QTimer.singleShot(FIRST_CHECK_MS, self.check_async)
self._timer = QTimer(self)
self._timer.setInterval(RECHECK_INTERVAL_MS)
self._timer.timeout.connect(self.check_async)
self._timer.start()
def check_async(self):
if self._busy:
return
self._busy = True
threading.Thread(target=self._check, daemon=True).start()
def update_async(self):
# The app is never replaced from inside: the button opens the page.
if self.release_mode or not self.enabled or self._busy:
return
self._busy = True
threading.Thread(target=self._update, daemon=True).start()
# ---- internals (run on daemon threads) ----
def _check(self):
if self.release_mode:
return self._check_release()
try:
if not self.enabled:
return
if self._git("fetch", "--quiet", timeout=60) is None:
return # offline / host unreachable — perfectly normal, stay quiet
behind = self._git("rev-list", "--count", "HEAD..@{upstream}")
if behind and behind.isdigit() and int(behind) > 0:
self.update_available.emit(int(behind))
finally:
self._busy = False
def _check_release(self):
"""Ask GitHub for the newest release; quiet on any failure."""
try:
found = fetch_latest_release()
if found and release_info.is_newer(found[0], __version__):
self.release_available.emit(*found)
finally:
self._busy = False
def _update(self):
try:
proc = subprocess.run(
["git", "-C", self._root, "pull", "--ff-only", "--quiet"],
capture_output=True, text=True, timeout=120)
if proc.returncode == 0:
self.update_applied.emit()
else:
lines = [l.strip() for l in
(proc.stderr or proc.stdout).strip().splitlines()
if l.strip()]
# git's actual reason is the error:/fatal: line, not the
# trailing "Aborting"
message = next(
(l for l in lines if l.startswith(("error:", "fatal:"))),
lines[-1] if lines else "git pull failed")
self.update_failed.emit(message)
except Exception as e:
self.update_failed.emit(str(e))
finally:
self._busy = False
def _git(self, *args, timeout=15) -> str | None:
"""Run git in the repo root; stripped stdout, or None on any failure."""
try:
proc = subprocess.run(["git", "-C", self._root, *args],
capture_output=True, text=True,
timeout=timeout)
except Exception:
return None
if proc.returncode != 0:
return None
return proc.stdout.strip()
def fetch_latest_release(repo: str | None = None, timeout: float = 20,
get=None) -> tuple[str, str] | None:
"""``(version, page url)`` of the newest GitHub release, or None when
checks are off, the network is down, or the answer is unusable.
Through ``requests`` rather than urllib: it carries certifi's CA
bundle, and a frozen Python's own OpenSSL may know no certificates.
No auth (60 requests an hour per address is plenty for one check
every four hours) and a User-Agent that says nothing about anyone.
"""
url = release_info.latest_release_url(repo)
if url is None:
return None
try:
if get is None:
import requests
get = requests.get
response = get(url, timeout=timeout, headers={
"Accept": "application/vnd.github+json",
"User-Agent": release_info.USER_AGENT,
})
if response.status_code != 200:
log.info("update check: HTTP %s", response.status_code)
return None
return release_info.parse_latest_release(response.json())
except Exception as e: # offline, DNS, bad JSON: all just "no news"
log.info("update check failed: %s", e)
return None