Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(tray): make update checks nonblocking and HiDPI-aware

Peach local maintenanceaa7e448cc7fc
diff --git a/README.md b/README.md
index 7d4e3f30f..5f0b7b6c8 100644
--- a/README.md
+++ b/README.md
@@ -46,8 +46,9 @@ cd R:\peach-app
`serve` 默认只监听 `127.0.0.1:8900`。公网、反代、HTTPS 和认证属于后续部署阶段,不在开发命令中隐式开启。
-Windows 日常运行使用登录后托盘,而不是保留命令行窗口或注册系统服务。托盘单击打开
-`https://peach.local/`,右键可查看状态、重启服务、打开日志、检查版本和退出;退出只结束
+Windows 日常运行使用登录后托盘,而不是保留命令行窗口或注册系统服务。托盘在启动时声明
+Per-Monitor V2 DPI,单击打开 `https://peach.local/`;右键可查看状态、重启服务、打开日志、
+查看版本/更新通道和退出。更新检查在后台运行并使用非模态系统通知;退出只结束
托盘自己启动的 Peach 进程:
```powershell
@@ -66,6 +67,10 @@ Windows 日常运行使用登录后托盘,而不是保留命令行窗口或注
`PEACH_LAN_ADDRESS`。它同时启动 HTTP `:80` 和本地 CA HTTPS `:443`,因此安装前必须先按
下文生成 TLS 材料。
+版本唯一来源是 `src/peach/__init__.py` 的 `__version__`,构建元数据由 setuptools 动态读取。
+托盘同时显示包版本、分支、提交、工作树状态和更新通道;没有 `origin` 时只报告本地开发版。
+即使发现远端提交也不会自动覆盖并行工作树。
+
需要本机 TLS 时同时提供证书和私钥;二者应放在 `R:\peach-data\secrets`,不要提交 Git:
```powershell
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 9ca8c6e6c..551e15563 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -237,6 +237,13 @@ Verified 2026-08-15 against the mihomo connection counter, five files plus a 115
Startup 中的 `Peach.lnk`,它用项目 venv 的 `pythonw.exe -m peach.tray` 启动交互式托盘;
不要同时新增系统服务、计划任务或注册表 Run 项。托盘单击打开 HTTPS,右键提供状态、
重启、日志、检查更新和退出。它用进程期文件锁拒绝重复实例,并只终止自己创建的服务进程。
+- 托盘必须在创建 Win32 窗口前启用 Per-Monitor V2 DPI;不要用清单缺失的 DPI-unaware
+ `pythonw` 进程让 Windows 位图缩放原生菜单。正常托盘动作不得弹模态 MessageBox。版本与
+ 更新子菜单读取缓存快照,显式检查在后台线程执行,通过 pystray 原生非模态通知反馈。
+- `src/peach/__init__.py::__version__` 是版本唯一来源,`pyproject.toml` 用 setuptools
+ dynamic attr 生成包版本,FastAPI 和托盘都读取同一值。当前采用 pre-1.0 SemVer:修复升
+ patch,兼容功能升 minor,破坏性数据/接口变化升 minor 并配 ADR/迁移。Git 提交是构建标识,
+ `vX.Y.Z` 是本地发布点。检查更新只 fetch/比较;自动安装在并行工作树模型下保持禁用。
- `scripts/manage_tray_startup.ps1` 是唯一自启动安装/状态/卸载入口。托盘同时管理 HTTP
`0.0.0.0:80`(负责 mDNS)和 HTTPS `192.168.50.162:443`;LAN 地址可用
`PEACH_LAN_ADDRESS` 覆盖。服务输出追加到 `R:\peach-data\logs\tray-*.log`。仓库当前没有
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 3aa0a29b9..b880addbf 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -31,7 +31,7 @@ These are product behavior and remain custom:
| Local file events | watchdog plus periodic reconciliation | media identity and missed-event repair |
| Transitional metadata/media | Stash GraphQL, CommunityScrapers and Stash job system | adapter, reconciliation and exit gates |
| LAN discovery | Python zeroconf | service lifecycle and real-client acceptance |
-| Windows tray | pystray 0.19.5 (LGPLv3) plus Pillow | Peach service ownership, menu actions and brand mark |
+| Windows tray | pystray 0.19.5 (LGPLv3), Pillow and Win32 Per-Monitor V2 DPI | Peach service ownership, background update check, menu actions and brand mark |
| Agent usage/quota | official provider quota APIs; T3 Code/CodexBar for local history | task routing, redaction and stale-snapshot labeling |
| Video source/end-card evidence | existing FFmpeg frame extraction plus a reviewed OCR/vision adapter | opening/ending sample policy, provenance and incomplete-version candidates |
| Referenced product behavior | current live interaction plus versioned public DOM/CSS/JS, or exact screenshot measurements when source is unavailable | evidence register, accessibility, Peach-specific deviations and regression checks |
diff --git a/docs/adr/0012-version-and-update-boundary.md b/docs/adr/0012-version-and-update-boundary.md
new file mode 100644
index 000000000..8e70b7792
--- /dev/null
+++ b/docs/adr/0012-version-and-update-boundary.md
@@ -0,0 +1,40 @@
+# ADR-0012:版本唯一来源与只检查更新边界
+
+- 状态:Accepted
+- 日期:2026-08-15
+
+## 背景
+
+Peach 曾同时在 `pyproject.toml`、`peach.__version__` 和 FastAPI 构造参数中保存版本,实际值
+分别为 0.2.0、0.1.0 和 0.2.0。托盘“检查更新”直接在 Win32 消息线程运行 Git,再弹模态
+MessageBox;仓库因 R: 盘所有权检查失败时只显示“无法读取”,确认框还会阻塞托盘交互。
+
+主仓库目前没有 Git remote,并且 Codex/Claude 使用独立工作树。自动 pull 或覆盖工作树既不是
+真实可用能力,也会破坏并行集成边界。
+
+## 决策
+
+- `src/peach/__init__.py::__version__` 是唯一版本来源;setuptools 通过 dynamic attr 生成包
+ 元数据,FastAPI health/OpenAPI 和托盘均读取同一值。
+- 采用 pre-1.0 SemVer。修复升 patch;兼容功能升 minor;破坏性数据或接口变化升 minor,且
+ 必须同时有 ADR、正式迁移和验收。发布提交使用本地 `vX.Y.Z` tag。
+- 托盘显示包版本、分支、八位提交、工作树状态和更新通道。所有 Git 读取显式传仓库级
+ `safe.directory`,不修改用户的全局 Git 配置。
+- 没有 `origin` 时报告“本地开发版、未配置更新源”。配置后,用户显式点击才在后台执行
+ `git fetch --prune origin`,然后比较当前分支与 upstream 的 ahead/behind。
+- 更新检查绝不 checkout、merge、pull、reset 或安装;发现更新只报告,由协调者按 worktree
+ 协议审核集成。
+- 托盘正常动作只使用 pystray 非模态系统通知。Git、网络和比较工作不得运行在托盘消息线程。
+
+## 已拒绝方案
+
+- **继续手工同步三处版本字符串**:已经实际漂移,无法作为发布依据。
+- **点击即 `git pull`**:会覆盖或冲突于用户和 agent 的在途修改。
+- **自建更新服务器/安装器**:当前没有可发布制品和远程通道,属于虚假复杂度。
+- **模态 MessageBox 报告普通状态**:会阻塞通知区消息循环,HiDPI 下还暴露缩放问题。
+
+## 后果
+
+0.2.1 起版本、API 和托盘一致;更新检查可真实区分未配置、最新、落后、领先和分叉,但保持
+只读。将来有签名制品和稳定 remote 后,可在新 ADR 中增加下载/验签/原子切换,不能直接扩展
+当前按钮为自动覆盖工作树。
diff --git a/pyproject.toml b/pyproject.toml
index 217d7b540..edb34fc88 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "peach-app"
-version = "0.2.0"
+dynamic = ["version"]
description = "Local-first media library, behavior ledger, and discovery application"
requires-python = ">=3.12"
dependencies = [
@@ -27,5 +27,8 @@ peach-tray = "peach.tray:main"
[tool.setuptools]
package-dir = {"" = "src"}
+[tool.setuptools.dynamic]
+version = {attr = "peach.__version__"}
+
[tool.setuptools.packages.find]
where = ["src"]
diff --git a/src/peach/__init__.py b/src/peach/__init__.py
index 85bfcaf9c..179111232 100644
--- a/src/peach/__init__.py
+++ b/src/peach/__init__.py
@@ -1,3 +1,3 @@
"""Peach application package."""
-__version__ = "0.1.0"
+__version__ = "0.2.1"
diff --git a/src/peach/api.py b/src/peach/api.py
index d8ba0c7ad..416caa6a6 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -7,7 +7,7 @@ from typing import Any
from fastapi import Body, FastAPI, Request
from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse, Response
-from . import web_contract
+from . import __version__, web_contract
from .config import PeachSettings
from .ffmpeg import FFmpegResolver
from .http import HttpxTransport
@@ -89,7 +89,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:
app = FastAPI(
title="Peach API",
- version="0.2.0",
+ version=__version__,
lifespan=lifespan,
docs_url="/docs" if settings.docs_enabled else None,
redoc_url=None,
@@ -119,7 +119,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:
def healthz() -> dict[str, Any]:
# 不探测/迁移数据库;健康检查必须无副作用。
ffmpeg = resolver.ffmpeg()
- return {"ok": True, "service": "peach-api", "mode": "fastapi",
+ return {"ok": True, "service": "peach-api", "version": __version__, "mode": "fastapi",
"db": "available" if settings.db_path.is_file() else "missing",
"ffmpeg": ffmpeg.source if ffmpeg else "unavailable",
"mdns": mdns.status if mdns is not None else "disabled",
diff --git a/src/peach/tray.py b/src/peach/tray.py
index b39756497..9b1c96d3f 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -16,12 +16,39 @@ import pystray
from PIL import Image, ImageDraw
from .config import LOG_DIR, PROJECT_ROOT, SECRETS_DIR, STATE_DIR
+from .versioning import VersionManager
DEFAULT_LAN_ADDRESS = "192.168.50.162"
OPEN_URL = "https://peach.local/"
+def enable_hidpi() -> str:
+ """Enable native sharp Win32 menus before pystray creates any windows."""
+ if os.name != "nt":
+ return "not-windows"
+ try:
+ setter = ctypes.windll.user32.SetProcessDpiAwarenessContext
+ setter.argtypes = [ctypes.c_void_p]
+ setter.restype = ctypes.c_bool
+ if setter(ctypes.c_void_p(-4)): # DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
+ return "per-monitor-v2"
+ except (AttributeError, OSError):
+ pass
+ try:
+ result = ctypes.windll.shcore.SetProcessDpiAwareness(2) # PROCESS_PER_MONITOR_DPI_AWARE
+ if result in (0, -2147024891): # S_OK or E_ACCESSDENIED (already set)
+ return "per-monitor"
+ except (AttributeError, OSError):
+ pass
+ try:
+ if ctypes.windll.user32.SetProcessDPIAware():
+ return "system"
+ except (AttributeError, OSError):
+ pass
+ return "unavailable"
+
+
@dataclass(frozen=True)
class ServiceSpec:
name: str
@@ -228,28 +255,21 @@ def show_message(title: str, message: str, *, error: bool = False) -> None:
print(f"{title}: {message}")
-def update_status() -> str:
- try:
- revision = subprocess.run(
- ["git", "-C", str(PROJECT_ROOT), "rev-parse", "--short", "HEAD"],
- capture_output=True, text=True, timeout=5, check=True,
- ).stdout.strip()
- remote = subprocess.run(
- ["git", "-C", str(PROJECT_ROOT), "remote", "get-url", "origin"],
- capture_output=True, text=True, timeout=5, check=False,
- )
- except (OSError, subprocess.SubprocessError):
- return "无法读取本地版本信息。"
- if remote.returncode != 0:
- return f"当前提交 {revision}。这是本地开发版,尚未配置更新源。"
- return f"当前提交 {revision}。已配置更新源;自动更新尚未启用,请由项目协调者审核更新。"
-
-
class PeachTray:
- def __init__(self, manager: ServiceManager) -> None:
+ def __init__(self, manager: ServiceManager, versions: VersionManager | None = None) -> None:
self.manager = manager
+ self.versions = versions or VersionManager()
+ self.version = self.versions.inspect()
self._stop_event = threading.Event()
self._restart_lock = threading.Lock()
+ self._update_lock = threading.Lock()
+ version_menu = pystray.Menu(
+ pystray.MenuItem(lambda _item: f"Peach {self.version.package_version}", None, enabled=False),
+ pystray.MenuItem(lambda _item: self.version.build_label, None, enabled=False),
+ pystray.MenuItem(lambda _item: self.version.channel_label, None, enabled=False),
+ pystray.Menu.SEPARATOR,
+ pystray.MenuItem("检查更新", self.check_updates),
+ )
self.icon = pystray.Icon(
"Peach",
create_icon(),
@@ -260,7 +280,7 @@ class PeachTray:
pystray.Menu.SEPARATOR,
pystray.MenuItem("重启服务", self.restart),
pystray.MenuItem("查看日志", self.open_logs),
- pystray.MenuItem("检查更新", self.check_updates),
+ pystray.MenuItem("版本与更新", version_menu),
pystray.Menu.SEPARATOR,
pystray.MenuItem("退出 Peach", self.exit),
),
@@ -281,7 +301,7 @@ class PeachTray:
return
(icon or self.icon).update_menu()
if not ready:
- show_message("Peach", "服务未能在 20 秒内恢复,请查看日志。", error=True)
+ (icon or self.icon).notify("服务未能在 20 秒内恢复,请查看日志。", "Peach")
finally:
self._restart_lock.release()
@@ -292,8 +312,22 @@ class PeachTray:
if os.name == "nt":
os.startfile(LOG_DIR)
- def check_updates(self, _icon=None, _item=None) -> None:
- show_message("Peach 更新", update_status())
+ def check_updates(self, icon=None, _item=None) -> None:
+ if not self._update_lock.acquire(blocking=False):
+ return
+ tray_icon = icon or self.icon
+ tray_icon.notify("正在检查更新…", "Peach")
+
+ def work() -> None:
+ try:
+ result = self.versions.check()
+ self.version = result.snapshot
+ tray_icon.update_menu()
+ tray_icon.notify(result.message, "Peach 版本与更新")
+ finally:
+ self._update_lock.release()
+
+ threading.Thread(target=work, name="PeachUpdate", daemon=True).start()
def exit(self, icon=None, _item=None) -> None:
self._stop_event.set()
@@ -306,18 +340,25 @@ class PeachTray:
self.manager.healthy(spec)
self.icon.update_menu()
+ def _setup(self, icon) -> None:
+ icon.visible = True
+ if self._startup_warning:
+ icon.notify(self._startup_warning, "Peach")
+
def run(self) -> None:
self.manager.start_missing()
+ self._startup_warning = None
if not self.manager.wait_until_ready():
- show_message("Peach", "Peach 只启动了部分服务,请查看托盘状态和日志。", error=True)
+ self._startup_warning = "Peach 只启动了部分服务,请查看托盘状态和日志。"
threading.Thread(target=self._monitor, name="PeachHealth", daemon=True).start()
try:
- self.icon.run()
+ self.icon.run(setup=self._setup)
finally:
self._stop_event.set()
def main() -> int:
+ enable_hidpi()
instance = SingleInstance(STATE_DIR / "peach-tray.lock")
manager = None
try:
diff --git a/src/peach/versioning.py b/src/peach/versioning.py
new file mode 100644
index 000000000..19b2102dc
--- /dev/null
+++ b/src/peach/versioning.py
@@ -0,0 +1,122 @@
+from __future__ import annotations
+
+import os
+import subprocess
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable
+
+from . import __version__
+from .config import PROJECT_ROOT
+
+
+@dataclass(frozen=True)
+class VersionSnapshot:
+ package_version: str
+ branch: str
+ commit: str
+ dirty: bool
+ remote_configured: bool
+ upstream: str | None
+
+ @property
+ def build_label(self) -> str:
+ dirty = " · 有未提交修改" if self.dirty else ""
+ return f"{self.branch}@{self.commit}{dirty}"
+
+ @property
+ def channel_label(self) -> str:
+ if not self.remote_configured:
+ return "本地开发版 · 未配置更新源"
+ if not self.upstream:
+ return "已配置更新源 · 未跟踪分支"
+ return f"更新通道 · {self.upstream}"
+
+
+@dataclass(frozen=True)
+class UpdateResult:
+ state: str
+ message: str
+ snapshot: VersionSnapshot
+ ahead: int = 0
+ behind: int = 0
+
+
+class VersionManager:
+ """Read-only Git/package version inspection and explicit update checks."""
+
+ def __init__(
+ self,
+ root: Path = PROJECT_ROOT,
+ *,
+ execute: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
+ ) -> None:
+ self.root = root.resolve()
+ self._execute = execute
+
+ def _git(self, *args: str, timeout: float = 8.0) -> subprocess.CompletedProcess[str]:
+ creationflags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
+ return self._execute(
+ [
+ "git", "-c", f"safe.directory={self.root.as_posix()}",
+ "-C", str(self.root), *args,
+ ],
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ check=False,
+ creationflags=creationflags,
+ )
+
+ def _text(self, *args: str) -> str:
+ result = self._git(*args)
+ return result.stdout.strip() if result.returncode == 0 else ""
+
+ def inspect(self) -> VersionSnapshot:
+ package_version = __version__
+ commit = self._text("rev-parse", "--short=8", "HEAD") or "unknown"
+ branch = self._text("branch", "--show-current") or "detached"
+ dirty = bool(self._text("status", "--porcelain"))
+ remote_configured = self._git("remote", "get-url", "origin").returncode == 0
+ upstream = self._text("rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}") or None
+ if remote_configured and upstream is None and branch != "detached":
+ candidate = f"origin/{branch}"
+ if self._git("show-ref", "--verify", f"refs/remotes/{candidate}").returncode == 0:
+ upstream = candidate
+ return VersionSnapshot(package_version, branch, commit, dirty, remote_configured, upstream)
+
+ def check(self) -> UpdateResult:
+ before = self.inspect()
+ if not before.remote_configured:
+ return UpdateResult(
+ "unconfigured",
+ f"Peach {before.package_version}({before.build_label})\n未配置更新源;当前为本地开发版。",
+ before,
+ )
+ fetched = self._git("fetch", "--quiet", "--prune", "origin", timeout=30)
+ if fetched.returncode != 0:
+ return UpdateResult("error", "无法连接更新源;本地版本未改变。", before)
+ current = self.inspect()
+ if not current.upstream:
+ return UpdateResult(
+ "untracked",
+ "更新源已连接,但当前分支没有对应的跟踪分支。",
+ current,
+ )
+ counts = self._text("rev-list", "--left-right", "--count", f"HEAD...{current.upstream}").split()
+ if len(counts) != 2 or not all(value.isdigit() for value in counts):
+ return UpdateResult("error", "更新源已连接,但无法比较版本。", current)
+ ahead, behind = map(int, counts)
+ if behind and ahead:
+ state = "diverged"
+ message = f"本地领先 {ahead} 个提交,远端领先 {behind} 个提交;需要人工合并。"
+ elif behind:
+ state = "available"
+ message = f"发现 {behind} 个新提交。为保护并行工作树,只检查、不自动安装。"
+ elif ahead:
+ state = "ahead"
+ message = f"当前已比更新通道领先 {ahead} 个提交。"
+ else:
+ state = "current"
+ message = f"Peach {current.package_version} 已是当前更新通道的最新版本。"
+ return UpdateResult(state, message, current, ahead=ahead, behind=behind)
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index c0bade08b..b5cfdfd6a 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -110,6 +110,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
response = await self.client.get("/healthz")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["mode"], "fastapi")
+ self.assertEqual(response.json()["version"], "0.2.1")
async def test_auth_and_items_contract(self):
denied = await self.client.get("/api/items")
diff --git a/tests/test_tray.py b/tests/test_tray.py
index 001615b19..fe32e209c 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -1,10 +1,15 @@
-import subprocess
import tempfile
+import threading
+import time
import unittest
from pathlib import Path
from unittest.mock import Mock, patch
-from peach.tray import AlreadyRunning, ServiceManager, ServiceSpec, SingleInstance, create_icon, update_status
+from peach.tray import (
+ AlreadyRunning, PeachTray, ServiceManager, ServiceSpec, SingleInstance,
+ create_icon, enable_hidpi,
+)
+from peach.versioning import UpdateResult, VersionSnapshot
class Response:
@@ -47,13 +52,33 @@ class TrayTests(unittest.TestCase):
manager.stop_owned()
process.terminate.assert_called_once()
- @patch("peach.tray.subprocess.run")
- def test_update_status_reports_missing_channel(self, run):
- run.side_effect = (
- subprocess.CompletedProcess([], 0, "abc123\n", ""),
- subprocess.CompletedProcess([], 2, "", "missing"),
- )
- self.assertIn("尚未配置更新源", update_status())
+ @patch("peach.tray.ctypes.windll.user32.SetProcessDpiAwarenessContext")
+ def test_hidpi_prefers_per_monitor_v2(self, set_context):
+ set_context.return_value = True
+ self.assertEqual(enable_hidpi(), "per-monitor-v2")
+
+ def test_update_check_is_background_notification_not_modal_dialog(self):
+ snapshot = VersionSnapshot("0.2.1", "master", "abc12345", False, False, None)
+ completed = threading.Event()
+
+ class Versions:
+ def inspect(self):
+ return snapshot
+
+ def check(self):
+ completed.set()
+ return UpdateResult("unconfigured", "未配置更新源", snapshot)
+
+ icon = Mock()
+ tray = PeachTray(ServiceManager(tuple()), Versions())
+ tray.check_updates(icon)
+ self.assertTrue(completed.wait(2))
+ for _ in range(20):
+ if icon.notify.call_count == 2:
+ break
+ time.sleep(0.01)
+ self.assertEqual(icon.notify.call_count, 2)
+ icon.update_menu.assert_called_once()
def test_single_instance_rejects_second_windows_lock(self):
with tempfile.TemporaryDirectory() as directory:
diff --git a/tests/test_versioning.py b/tests/test_versioning.py
new file mode 100644
index 000000000..c70cb7b8b
--- /dev/null
+++ b/tests/test_versioning.py
@@ -0,0 +1,81 @@
+import os
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from peach.versioning import VersionManager
+
+
+def git(path: Path, *args: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["git", "-c", f"safe.directory={path.as_posix()}", "-C", str(path), *args],
+ capture_output=True, text=True, check=True,
+ )
+
+
+def initialize_repo(path: Path) -> None:
+ subprocess.run(["git", "init", "-b", "master", str(path)], capture_output=True, check=True)
+ git(path, "config", "user.name", "Peach Tests")
+ git(path, "config", "user.email", "[email protected]")
+ (path / "version.txt").write_text("one\n", encoding="utf-8")
+ git(path, "add", "version.txt")
+ git(path, "commit", "-m", "initial")
+
+
+class VersionManagerTests(unittest.TestCase):
+ def test_local_development_version_is_readable_without_remote(self):
+ with tempfile.TemporaryDirectory() as directory:
+ repo = Path(directory) / "repo"
+ initialize_repo(repo)
+ manager = VersionManager(repo)
+ snapshot = manager.inspect()
+ self.assertEqual(snapshot.branch, "master")
+ self.assertNotEqual(snapshot.commit, "unknown")
+ self.assertFalse(snapshot.remote_configured)
+ result = manager.check()
+ self.assertEqual(result.state, "unconfigured")
+ self.assertIn("本地开发版", result.message)
+
+ def test_check_fetches_and_reports_remote_commits_without_applying(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ remote = root / "remote.git"
+ repo = root / "repo"
+ other = root / "other"
+ test_config = root / "gitconfig"
+ test_config.write_text(
+ "[safe]\n"
+ f"\tdirectory = {repo.as_posix()}\n"
+ f"\tdirectory = {remote.as_posix()}\n"
+ f"\tdirectory = {other.as_posix()}\n",
+ encoding="utf-8",
+ )
+ safe_directories = {
+ "GIT_CONFIG_GLOBAL": str(test_config),
+ "GIT_CONFIG_NOSYSTEM": "1",
+ }
+ with mock.patch.dict(os.environ, safe_directories):
+ subprocess.run(["git", "init", "--bare", str(remote)], capture_output=True, check=True)
+ initialize_repo(repo)
+ git(repo, "remote", "add", "origin", str(remote))
+ git(repo, "push", "-u", "origin", "master")
+ subprocess.run(["git", "clone", str(remote), str(other)], capture_output=True, check=True)
+ git(other, "config", "user.name", "Peach Tests")
+ git(other, "config", "user.email", "[email protected]")
+ (other / "version.txt").write_text("two\n", encoding="utf-8")
+ git(other, "add", "version.txt")
+ git(other, "commit", "-m", "remote update")
+ git(other, "push", "origin", "master")
+
+ before = git(repo, "rev-parse", "HEAD").stdout.strip()
+ result = VersionManager(repo).check()
+ after = git(repo, "rev-parse", "HEAD").stdout.strip()
+ self.assertEqual(result.state, "available")
+ self.assertEqual(result.behind, 1)
+ self.assertEqual(before, after)
+
+
+if __name__ == "__main__":
+ unittest.main()