Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(init): 不带参数的 peach init 进入首次运行问答,新增 peach scan

longmeidao11bfda614396
diff --git a/src/peach/cli.py b/src/peach/cli.py
index d766f4870..af4e9aeba 100644
--- a/src/peach/cli.py
+++ b/src/peach/cli.py
@@ -2,10 +2,11 @@ from __future__ import annotations
import argparse
import os
+import sys
from datetime import datetime
from pathlib import Path
-from . import certs, settings_file
+from . import certs, onboarding, scan, settings_file
from .api import create_app
from .config import (
DATABASE_PATH,
@@ -21,6 +22,7 @@ from .config import (
)
from .follow_cli import register as register_follow
from .migrations import plan, upgrade
+from .platform import location_mounts
from .scripting import open_readonly
from .sync import LedgerSync, device_id
from .sync import plan as sync_plan
@@ -278,7 +280,12 @@ def _init(args: argparse.Namespace) -> int:
证书,只把当前生效的配置落成设置文件。现有部署的坐标散在环境变量和运行现场里,
进程看不见的那几项(局域网地址、钥匙串账号名)由命令行显式补,落不下的会在末尾
逐条列出来,绝不拿猜的值填。
+
+ 一个参数都没给、stdin 又是终端时进问答(`_init_interactive`);给了任何参数、
+ 加了 `--no-input` 或 stdin 不是终端,都走下面这条非交互路径。
"""
+ if _wants_interview(args):
+ return _init_interactive()
config, broken = _resolved_config(args.data_root)
if config.path.exists() and not args.force:
print(f"设置文件已存在:{config.path}")
@@ -316,6 +323,89 @@ def _init(args: argparse.Namespace) -> int:
return 0
+def _wants_interview(args: argparse.Namespace) -> bool:
+ """`peach init` 不带任何参数、stdin 是终端,才进问答。
+
+ 「不带任何参数」按 parser 的默认值判,不另抄一份参数名:加一个开关就多一处要同步。
+ `--no-input` 本身就是一个参数,所以它天然落到非交互路径。
+ """
+ bare = build_parser().parse_args(["init"])
+ return vars(args) == vars(bare) and onboarding.is_interactive(sys.stdin)
+
+
+def _init_interactive(
+ ask: onboarding.Ask = onboarding.console_ask, *,
+ windows: bool | None = None, home: Path | None = None,
+) -> int:
+ """首次运行问答。题目、校验与落盘全在 `peach.onboarding`,这里只是终端前端。
+
+ `ask`、`windows`、`home` 可注入:测试用脚本化答案驱动,不碰真实 stdin,也不看
+ 测试机自己是什么系统。托盘的设置页复用同一组函数,不走这个入口。
+ """
+ windows = os.name == "nt" if windows is None else windows
+ config, _broken = _resolved_config(None)
+ print("首次运行问答:每一题直接回车就接受方括号里的默认值。")
+ try:
+ answers = onboarding.interview(config, ask, windows=windows, home=home)
+ except onboarding.OnboardingAborted as exc:
+ raise SystemExit(f"{exc}已退出,没有写任何文件。") from None
+ config, _broken = _resolved_config(answers.data_root)
+ if config.path.exists():
+ print(f"设置文件已存在:{config.path}")
+ print("要重新生成就跑 `peach init --force`;它会覆盖这个文件,不动数据。")
+ return 3
+ prepared = onboarding.configure(config, answers, windows=windows)
+ _create_data_tree(prepared)
+ path = settings_file.write(prepared)
+ print(f"设置文件:{path}")
+ if not windows:
+ print(onboarding.mounts_explanation(answers.media_dir))
+
+ summary = None
+ try:
+ scan_now = onboarding.ask_until_valid(onboarding.scan_question(answers.media_dir), ask)
+ except onboarding.OnboardingAborted as exc:
+ print(f"{exc}跳过扫描,之后可以跑 `peach scan local`。")
+ scan_now = False
+ if scan_now:
+ result = scan.scan_location(
+ prepared.directory("database") / "ledger.db", onboarding.LOCAL_LOCATION,
+ onboarding.scan_root(prepared), declared_roots=prepared.locations,
+ mounts=prepared.mounts, report=print, windows=windows,
+ )
+ summary = result.summary()
+ _print_next_steps(prepared, from_existing=False)
+ if summary:
+ print(f" 扫描结果:{summary}")
+ return 0
+
+
+def _scan(args: argparse.Namespace) -> int:
+ """`peach scan <来源ID> [根目录]`:根目录省略时取该来源的声明根(本机目录按挂载表取)。"""
+ _require_readable_settings()
+ if not args.db.is_file():
+ print(f"账本不存在:{args.db}")
+ print("这台机器还没初始化过,先跑 `peach init`。")
+ return 4
+ config = settings_file.active()
+ mounts = {location: str(mount) for location, mount in location_mounts().items()}
+ try:
+ if args.root is None:
+ if args.location not in config.locations:
+ known = "、".join(sorted(config.locations)) or "(设置文件里一个都没有)"
+ raise scan.ScanTargetError(
+ f"✗ 未声明的来源 {args.location!r};[media.locations] 里已知:{known}")
+ root = config.locations[args.location]
+ else:
+ root = scan.ledger_root_for(
+ args.location, args.root, declared_roots=config.locations, mounts=mounts)
+ scan.scan_location(args.db, args.location, root, declared_roots=config.locations,
+ mounts=mounts, report=lambda line: print(line, flush=True))
+ except scan.ScanTargetError as exc:
+ raise SystemExit(str(exc)) from None
+ return 0
+
+
def _create_data_tree(config: settings_file.PeachConfig) -> None:
"""建目录、把库迁到最新、生成本机 CA。已经有账本就不碰它。"""
for key in settings_file.DIRECTORY_KEYS:
@@ -383,7 +473,10 @@ def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="peach")
commands = parser.add_subparsers(dest="command", required=True)
- init = commands.add_parser("init", help="首次运行:建数据目录、建库、写设置文件")
+ init = commands.add_parser(
+ "init", help="首次运行:不带参数在终端里问答;带任何参数或 --no-input 走非交互")
+ init.add_argument("--no-input", action="store_true",
+ help="不进入问答,按参数与内建默认直接生成")
init.add_argument("--data-root", type=Path, help="数据根;默认沿用当前发现结果")
init.add_argument("--from-existing", action="store_true",
help="只为已在运行的部署生成设置文件,不建目录、不建库")
@@ -418,6 +511,14 @@ def build_parser() -> argparse.ArgumentParser:
serve.add_argument("--ssl-keyfile", type=Path)
serve.set_defaults(handler=_serve)
+ scan_parser = commands.add_parser(
+ "scan", help="扫描一个来源的目录,把文件元数据写进账本")
+ scan_parser.add_argument("location", help="来源 ID(asset.location),要在 [media.locations] 里声明过")
+ scan_parser.add_argument("root", nargs="?",
+ help="要扫的目录;省略时取该来源的声明根(本机目录按 [media.mounts] 取)")
+ scan_parser.add_argument("--db", type=Path, default=DEFAULT_DB)
+ scan_parser.set_defaults(handler=_scan)
+
migrate = commands.add_parser("migrate", help="inspect or apply SQLite migrations")
migrate.add_argument("action", choices=("status", "upgrade"), nargs="?", default="status")
migrate.add_argument("--db", type=Path, default=DEFAULT_DB)
diff --git a/src/peach/onboarding.py b/src/peach/onboarding.py
new file mode 100644
index 000000000..be32b65b4
--- /dev/null
+++ b/src/peach/onboarding.py
@@ -0,0 +1,247 @@
+"""首次运行问答:问什么、怎么校验、写出什么样的设置文件。
+
+这里只有纯逻辑,不碰终端:`peach init` 的命令行问答是它的第一个前端,托盘首启打开的
+设置页是第二个,两边都调同一组函数——`questions()` 给出题目、默认值和校验器,
+`interview()` 用注入的 `ask` 把题目走一遍,`configure()` 把答案落成 `PeachConfig`。
+前端只负责把字串送进来、把错误显示出去。
+
+问答刻意只收最小集合:数据根、一个本地媒体目录、监听范围、端口、局域网名字。复制、
+115、PikPak、writer 镜像与 SMB 一律保持默认关闭或留空——陌生人第一次跑不该被这些问题
+拦住,设置文件里也只写用户声明过的来源,不把维护者的示例盘符写进别人的文件。
+
+媒体目录在两个平台上落成不同的写法,因为账本路径的形状是不变量(AGENTS.md):
+
+- Windows:盘符本身就是挂载点,`[media.locations] local = <该目录>`,`[media.mounts]` 留空。
+- macOS:声明根仍写账本口径的 `R:\\media`,`[media.mounts] local = <该目录>`,读取侧
+ 按「声明根前缀 → 本机挂载点」翻译(`peach.platform`),扫描侧按同一规则反着写(`peach.scan`)。
+"""
+from __future__ import annotations
+
+import re
+from collections.abc import Callable
+from dataclasses import dataclass, replace
+from pathlib import Path
+
+from . import settings_file
+from .platform import is_windows_path
+from .settings_file import PeachConfig
+
+#: 提问函数:(题目, 默认值) -> 用户输入的原文。空串表示接受默认值。
+Ask = Callable[[str, str], str]
+
+LOOPBACK_HOST = "127.0.0.1"
+LAN_HOST = "0.0.0.0"
+#: 每题最多问几次。三次都不是有效值就放弃,不能让人困在一个死循环里。
+MAX_ATTEMPTS = 3
+#: 非 Windows 平台上本地来源的账本口径声明根。账本一律 Windows 形态,这个值只是个前缀,
+#: 真正的目录由 `[media.mounts] local` 给出。
+POSIX_LOCAL_DECLARED_ROOT = r"R:\media"
+#: 本地来源的 ID。v1 只收一个目录,它就是 `asset.location = 'local'`。
+LOCAL_LOCATION = "local"
+
+_DNS_LABEL = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")
+_HOST_CHOICES = {
+ "1": LOOPBACK_HOST, "本机": LOOPBACK_HOST, LOOPBACK_HOST: LOOPBACK_HOST,
+ "2": LAN_HOST, "局域网": LAN_HOST, LAN_HOST: LAN_HOST,
+}
+_YES = {"", "y", "yes", "是"}
+_NO = {"n", "no", "否"}
+
+
+class OnboardingAborted(RuntimeError):
+ """一题没有问出有效答案:连续给错、或者输入结束。消息以句号结尾,前端接着说后果。"""
+
+
+@dataclass(frozen=True)
+class Question:
+ key: str
+ prompt: str
+ default: str
+ #: 原文 -> 规范值;不合格就抛 `ValueError`,消息直接给人看。
+ validate: Callable[[str], object]
+
+
+@dataclass(frozen=True)
+class Answers:
+ data_root: Path
+ media_dir: Path
+ host: str
+ port: int
+ mdns_name: str
+
+
+# --------------------------------------------------------------------------- 校验
+
+def validate_data_root(raw: str) -> Path:
+ text = raw.strip()
+ if not text:
+ raise ValueError("数据根不能为空")
+ path = Path(text).expanduser()
+ if path.is_file():
+ raise ValueError(f"{path} 是一个文件,数据根要是目录")
+ return path
+
+
+def media_dir_validator(*, windows: bool) -> Callable[[str], Path]:
+ def validate(raw: str) -> Path:
+ text = raw.strip()
+ if not text:
+ raise ValueError("媒体目录不能为空")
+ path = Path(text).expanduser()
+ if not path.is_dir():
+ raise ValueError(f"目录不存在或不是目录:{path}(这里不会替你创建)")
+ resolved = path.resolve()
+ if windows and not is_windows_path(str(resolved)):
+ raise ValueError(f"{resolved} 不是盘符路径;网络位置先映射成盘符再来")
+ return resolved
+ return validate
+
+
+def validate_host(raw: str) -> str:
+ key = raw.strip().lower()
+ try:
+ return _HOST_CHOICES[key]
+ except KeyError:
+ raise ValueError("填 1(仅本机)或 2(局域网)") from None
+
+
+def validate_port(raw: str) -> int:
+ text = raw.strip()
+ if not text.isdigit() or not 1 <= int(text) <= 65535:
+ raise ValueError("端口要是 1 到 65535 之间的整数")
+ return int(text)
+
+
+def validate_mdns_name(raw: str) -> str:
+ text = raw.strip()
+ if not _DNS_LABEL.match(text):
+ raise ValueError("名字只能用字母、数字和连字符,不能以连字符开头或结尾")
+ return text
+
+
+def validate_yes_no(raw: str) -> bool:
+ key = raw.strip().lower()
+ if key in _YES:
+ return True
+ if key in _NO:
+ return False
+ raise ValueError("填 y 或 n")
+
+
+# --------------------------------------------------------------------------- 题目
+
+def default_media_dir(home: Path, *, windows: bool) -> Path | None:
+ """系统自带的视频目录存在就拿来当默认值;不存在就没有默认,必须手填。"""
+ candidate = home / ("Videos" if windows else "Movies")
+ return candidate if candidate.is_dir() else None
+
+
+def questions(
+ config: PeachConfig, *, windows: bool, home: Path | None = None,
+) -> tuple[Question, ...]:
+ """按顺序给出全部题目。默认值来自当前解析到的配置,和非交互 `peach init` 同一口径。"""
+ home = Path.home() if home is None else home
+ media_default = default_media_dir(home, windows=windows)
+ return (
+ Question("data_root", "数据根(账本、缓存与设置文件都放这里)",
+ str(config.data_root), validate_data_root),
+ Question("media_dir", "本地媒体目录(来源 local,必须已存在)",
+ str(media_default) if media_default else "",
+ media_dir_validator(windows=windows)),
+ Question("host", "监听范围:1 = 仅本机(127.0.0.1),2 = 局域网(0.0.0.0)",
+ "1", validate_host),
+ Question("port", "服务端口", str(config.server.port), validate_port),
+ Question("mdns_name", "局域网名字(<名字>.local,只在监听局域网时发布)",
+ config.server.mdns_name, validate_mdns_name),
+ )
+
+
+def scan_question(media_dir: Path) -> Question:
+ return Question("scan_now", f"现在扫描 {media_dir}?(Y/n)", "Y", validate_yes_no)
+
+
+def ask_until_valid(
+ question: Question, ask: Ask, *, report: Callable[[str], None] = print,
+ max_attempts: int = MAX_ATTEMPTS,
+) -> object:
+ """问到拿到合格答案为止,最多 `max_attempts` 次;空输入取默认值。"""
+ for attempt in range(1, max_attempts + 1):
+ raw = ask(question.prompt, question.default)
+ candidate = raw if raw.strip() else question.default
+ try:
+ return question.validate(candidate)
+ except ValueError as exc:
+ remaining = max_attempts - attempt
+ report(f" {exc}" + (f"(还可以再试 {remaining} 次)" if remaining else ""))
+ raise OnboardingAborted(f"「{question.prompt}」连续 {max_attempts} 次没有拿到有效值。")
+
+
+def interview(
+ config: PeachConfig, ask: Ask, *, windows: bool, home: Path | None = None,
+ report: Callable[[str], None] = print, max_attempts: int = MAX_ATTEMPTS,
+) -> Answers:
+ """把全部题目走一遍。`ask` 由前端注入,测试用脚本化答案驱动。"""
+ answers: dict[str, object] = {}
+ for question in questions(config, windows=windows, home=home):
+ answers[question.key] = ask_until_valid(
+ question, ask, report=report, max_attempts=max_attempts)
+ return Answers(**answers) # type: ignore[arg-type]
+
+
+# --------------------------------------------------------------------------- 落盘
+
+def configure(config: PeachConfig, answers: Answers, *, windows: bool) -> PeachConfig:
+ """把答案落成一份可写回的设置。`config` 要按 `answers.data_root` 重新解析过。
+
+ 只写用户声明过的来源:`[media.locations]` 里只有 `local`。复制保持关闭,writer 镜像
+ 与 SMB 坐标留空,目录键全部落成显式值——和非交互 `peach init` 同一形状。
+ """
+ if windows:
+ locations = {LOCAL_LOCATION: str(answers.media_dir)}
+ mounts: dict[str, str] = {}
+ else:
+ locations = {LOCAL_LOCATION: POSIX_LOCAL_DECLARED_ROOT}
+ mounts = {LOCAL_LOCATION: str(answers.media_dir)}
+ prepared = settings_file.capture_existing(
+ config, replication_enabled=False,
+ overrides={"host": answers.host, "port": answers.port,
+ "mdns_name": answers.mdns_name},
+ mounts=mounts,
+ )
+ return replace(prepared, locations=locations)
+
+
+def scan_root(config: PeachConfig) -> str:
+ """首次扫描的账本口径根:就是 `local` 的声明根。本机目录由 `peach.scan` 按挂载表取。"""
+ return config.locations[LOCAL_LOCATION]
+
+
+def mounts_explanation(media_dir: Path) -> str:
+ """非 Windows 平台写出的两行为什么长那样,一句话说清。"""
+ return (f"账本用统一的 Windows 形态记路径({POSIX_LOCAL_DECLARED_ROOT}\\...),"
+ f"本机挂载点 [media.mounts] local = {media_dir} 负责翻译成真实文件。")
+
+
+def console_ask(prompt: str, default: str) -> str:
+ """终端前端:把默认值放在方括号里,回车即接受;输入结束视为放弃。"""
+ suffix = f" [{default}]" if default else "(必填)"
+ try:
+ return input(f"{prompt}{suffix}: ")
+ except EOFError:
+ raise OnboardingAborted("输入已结束。") from None
+
+
+def is_interactive(stdin) -> bool:
+ """stdin 是不是一个真的终端。管道、重定向和没有 stdin 的打包进程都不是。"""
+ try:
+ return bool(stdin is not None and stdin.isatty())
+ except (AttributeError, ValueError, OSError):
+ return False
+
+
+__all__ = [
+ "Answers", "Ask", "LOCAL_LOCATION", "MAX_ATTEMPTS", "OnboardingAborted",
+ "POSIX_LOCAL_DECLARED_ROOT", "Question", "ask_until_valid", "configure",
+ "console_ask", "default_media_dir", "interview", "is_interactive",
+ "mounts_explanation", "questions", "scan_question", "scan_root",
+]
diff --git a/src/peach/settings_file.py b/src/peach/settings_file.py
index 7ec3511e5..6685c3aa4 100644
--- a/src/peach/settings_file.py
+++ b/src/peach/settings_file.py
@@ -254,9 +254,13 @@ def _merge(
"路径填该来源的声明根在本机的落点,例如 "
"`local = '/mnt/media'`"
))
- locations = dict(DEFAULT_LOCATION_ROOTS)
- locations.update(
- _string_map(_table(media, _LOCATIONS_KEY, path), path, "media.locations."))
+ # 文件里写了 `[media.locations]` 就以它为准:`peach init` 的问答只声明用户给过的
+ # 来源,内建默认那三个示例盘符不能从旁边混进来,否则陌生人的机器上会多出两个
+ # 永远脱盘的来源。没写这张表才退回内建默认。
+ if _LOCATIONS_KEY in media:
+ locations = _string_map(_table(media, _LOCATIONS_KEY, path), path, "media.locations.")
+ else:
+ locations = dict(DEFAULT_LOCATION_ROOTS)
mounts = _string_map(_table(media, _MOUNTS_KEY, path), path, "media.mounts.")
unknown_mounts = sorted(set(mounts) - set(locations))
if unknown_mounts:
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 4fc9d85ea..5bae3ce9d 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -8,19 +8,23 @@ from __future__ import annotations
import argparse
import importlib.util
import io
+import os
import sqlite3
import tempfile
import unittest
from contextlib import redirect_stdout
-from pathlib import Path
+from dataclasses import replace
+from pathlib import Path, PureWindowsPath
from unittest import mock
-from peach import cli, settings_file
+from peach import cli, onboarding, settings_file
from peach.migrations import plan, upgrade
ROOT = Path(__file__).resolve().parents[1]
MIGRATIONS = ROOT / "migrations"
+HAS_HTTP_DEPS = all(importlib.util.find_spec(name) for name in ("fastapi", "httpx"))
+
def load_script(name: str):
path = ROOT / "scripts" / f"{name}.py"
@@ -216,6 +220,264 @@ class InitCommandTests(unittest.TestCase):
self.assertIn("--from-existing", output)
+class InteractiveInitTests(unittest.TestCase):
+ """`peach init` 不带参数、stdin 是终端时的问答流。
+
+ 答案脚本化、平台注入:Windows 形态与 POSIX 形态各走一条,不看测试机自己是什么。
+ """
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name).resolve()
+ self.data_root = self.root / "peach-data"
+ self.home = self.root / "home"
+ self.home.mkdir()
+ self.media = self.root / "media"
+ (self.media / "sub").mkdir(parents=True)
+ (self.media / "sub" / "a.mp4").write_bytes(b"0" * 10)
+ (self.media / "b.jpg").write_bytes(b"1")
+ patcher = mock.patch.object(cli.certs, "bootstrap_certificates")
+ self.certs = patcher.start()
+ self.addCleanup(patcher.stop)
+ # 第一题的默认值要落在临时目录里,回车接受默认才不会碰真实数据根。
+ env = mock.patch.dict(os.environ, {"PEACH_DATA_ROOT": str(self.data_root)})
+ env.start()
+ self.addCleanup(env.stop)
+
+ def _run(self, answers, *, windows):
+ queue = list(answers)
+ prompts: list[str] = []
+
+ def ask(prompt: str, default: str) -> str:
+ prompts.append(prompt)
+ return queue.pop(0)
+
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = cli._init_interactive(ask, windows=windows, home=self.home)
+ return code, output.getvalue(), prompts
+
+ def _ledger_paths(self):
+ connection = sqlite3.connect(self.data_root / "database" / "ledger.db")
+ try:
+ return sorted(row[0] for row in connection.execute("SELECT path FROM asset"))
+ finally:
+ connection.close()
+
+ def _loaded(self):
+ return settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.data_root)})
+
+ def test_windows_flow_declares_the_directory_and_scans_it(self):
+ code, output, prompts = self._run(["", str(self.media), "", "", "", ""], windows=True)
+ self.assertEqual(code, 0)
+ self.assertEqual(len(prompts), 6)
+ self.assertTrue(prompts[-1].startswith("现在扫描 "))
+ loaded = self._loaded()
+ self.assertTrue(loaded.present)
+ self.assertEqual(loaded.locations, {"local": str(self.media)})
+ self.assertEqual(loaded.mounts, {})
+ self.assertEqual((loaded.server.host, loaded.server.port, loaded.server.mdns_name),
+ ("127.0.0.1", 8900, "peach"))
+ self.assertFalse(loaded.replication.enabled)
+ for key in settings_file.DIRECTORY_KEYS:
+ self.assertTrue((self.data_root / key).is_dir(), key)
+ self.certs.assert_called_once()
+ # 账本里的路径就是本机路径,每一行都指向真实文件。
+ self.assertEqual(self._ledger_paths(),
+ sorted([str(self.media / "b.jpg"), str(self.media / "sub" / "a.mp4")]))
+ self.assertIn("✓ local: 2 文件", output)
+ self.assertIn("下一步", output)
+ self.assertIn("扫描结果:", output)
+ self.assertNotIn("115", (self.data_root / "config.toml").read_text(encoding="utf-8"))
+
+ def test_posix_flow_keeps_the_ledger_shape_and_mounts_the_directory(self):
+ code, output, _ = self._run(["", str(self.media), "2", "9443", "peach-two", ""],
+ windows=False)
+ self.assertEqual(code, 0)
+ loaded = self._loaded()
+ self.assertEqual(loaded.locations, {"local": r"R:\media"})
+ self.assertEqual(loaded.mounts, {"local": str(self.media)})
+ self.assertEqual((loaded.server.host, loaded.server.port, loaded.server.mdns_name),
+ ("0.0.0.0", 9443, "peach-two"))
+ self.assertIn("本机挂载点", output)
+ paths = self._ledger_paths()
+ self.assertEqual(paths, [r"R:\media\b.jpg", r"R:\media\sub\a.mp4"])
+ # 读取侧按同一套规则翻回去:声明根后的层级接到挂载点上。
+ for path in paths:
+ tail = PureWindowsPath(path).relative_to(PureWindowsPath(r"R:\media")).parts
+ self.assertTrue(Path(loaded.mounts["local"]).joinpath(*tail).is_file(), path)
+
+ def test_an_invalid_media_directory_is_asked_again(self):
+ missing = self.root / "nope"
+ code, output, prompts = self._run(
+ ["", str(missing), str(self.media), "", "", "", "n"], windows=True)
+ self.assertEqual(code, 0)
+ self.assertEqual(prompts.count("本地媒体目录(来源 local,必须已存在)"), 2)
+ self.assertIn("目录不存在", output)
+ self.assertFalse(missing.exists(), "问答不替人建媒体目录")
+
+ def test_three_bad_answers_abort_before_anything_is_written(self):
+ with self.assertRaises(SystemExit) as caught:
+ self._run(["", "/nope1", "/nope2", "/nope3"], windows=True)
+ self.assertIn("3 次", str(caught.exception))
+ self.assertIn("没有写任何文件", str(caught.exception))
+ self.assertFalse(self.data_root.exists())
+
+ def test_the_scan_can_be_declined(self):
+ code, output, _ = self._run(["", str(self.media), "", "", "", "n"], windows=True)
+ self.assertEqual(code, 0)
+ self.assertEqual(self._ledger_paths(), [])
+ self.assertNotIn("扫描结果", output)
+ self.assertIn("下一步", output)
+
+ def test_an_existing_settings_file_is_not_overwritten(self):
+ self.data_root.mkdir()
+ (self.data_root / "config.toml").write_text("[server]\nport = 9100\n", encoding="utf-8")
+ code, output, _ = self._run(["", str(self.media), "", "", ""], windows=True)
+ self.assertEqual(code, 3)
+ self.assertIn("已存在", output)
+ self.assertEqual((self.data_root / "config.toml").read_text(encoding="utf-8"),
+ "[server]\nport = 9100\n")
+
+ @unittest.skipUnless(HAS_HTTP_DEPS, "需要 fastapi 与 httpx")
+ def test_a_config_declaring_only_local_serves_health_items_and_sources(self):
+ """只声明 `local` 的设置文件要能直接起服务:没有 115/pikpak 不是错误。"""
+ import asyncio
+
+ import httpx
+
+ from peach import routes_api, web_resource_sync
+ from peach.api import create_app
+ from peach.config import PeachSettings
+ from peach.platform import translate_roots
+
+ self._run(["", str(self.media), "", "", "", ""], windows=True)
+ loaded = self._loaded()
+ settings = PeachSettings(
+ db_path=loaded.directory("database") / "ledger.db", configured=True, token="secret",
+ allowed_media_roots=translate_roots(tuple(loaded.locations.values())),
+ )
+
+ async def probe():
+ app = create_app(settings)
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),
+ base_url="http://test") as client:
+ health = await client.get("/healthz")
+ items = await client.get("/api/items?limit=10", headers={"Cookie": "tok=secret"})
+ sources = await client.get("/api/sources", headers={"Cookie": "tok=secret"})
+ return health, items, sources
+
+ with mock.patch.object(routes_api, "LOCATION_ROOT_DECLARATIONS", dict(loaded.locations)), \
+ mock.patch.object(web_resource_sync, "LOCATION_ROOT_DECLARATIONS",
+ dict(loaded.locations)):
+ health, items, sources = asyncio.run(probe())
+ self.assertEqual(health.status_code, 200)
+ self.assertEqual(items.status_code, 200)
+ self.assertGreaterEqual(items.json()["total"], 1, "扫进去的本地资产要能列出来")
+ self.assertEqual(sources.status_code, 200)
+ self.assertEqual([row["location"] for row in sources.json()["sources"]], ["local"])
+ self.assertTrue(web_resource_sync.source_is_online("local"))
+ self.assertFalse(web_resource_sync.source_is_online("115"))
+
+
+class InitDispatchTests(unittest.TestCase):
+ """问答只在「不带任何参数且 stdin 是终端」时进入;其余一律走非交互路径。"""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name).resolve() / "peach-data"
+ patcher = mock.patch.object(cli, "_init_interactive", return_value=0)
+ self.interactive = patcher.start()
+ self.addCleanup(patcher.stop)
+ certs = mock.patch.object(cli.certs, "bootstrap_certificates")
+ certs.start()
+ self.addCleanup(certs.stop)
+
+ def _run(self, argv, *, tty):
+ with mock.patch.object(onboarding, "is_interactive", return_value=tty), \
+ redirect_stdout(io.StringIO()):
+ return cli.main(argv)
+
+ def test_bare_init_on_a_terminal_enters_the_interview(self):
+ self.assertEqual(self._run(["init"], tty=True), 0)
+ self.interactive.assert_called_once_with()
+
+ def test_bare_init_without_a_terminal_stays_non_interactive(self):
+ with mock.patch.dict(os.environ, {"PEACH_DATA_ROOT": str(self.root)}):
+ self.assertEqual(self._run(["init"], tty=False), 0)
+ self.interactive.assert_not_called()
+ self.assertTrue((self.root / "config.toml").is_file())
+
+ def test_any_argument_or_no_input_stays_non_interactive(self):
+ self.assertEqual(self._run(["init", "--data-root", str(self.root)], tty=True), 0)
+ self.assertEqual(
+ self._run(["init", "--data-root", str(self.root), "--no-input", "--force"], tty=True), 0)
+ self.interactive.assert_not_called()
+ loaded = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(self.root)})
+ # 非交互路径的形状不变:三个来源的默认声明根照旧写出。
+ self.assertEqual(set(loaded.locations), {"local", "115", "pikpak"})
+
+
+class ScanCommandTests(unittest.TestCase):
+ """`peach scan <来源ID> [根目录]`:根目录省略时取设置文件里的声明根。"""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name).resolve()
+ self.db = self.root / "ledger.db"
+ upgrade(self.db, MIGRATIONS)
+ self.media = self.root / "media"
+ (self.media / "sub").mkdir(parents=True)
+ (self.media / "sub" / "a.mp4").write_bytes(b"0")
+ (self.media / "b.jpg").write_bytes(b"1")
+ config = settings_file.load_config(environ={}, strict=False)
+ fixed = replace(config, locations={"local": str(self.media)})
+ for target in (mock.patch.object(settings_file, "active", lambda: fixed),
+ mock.patch.object(cli, "location_mounts", lambda: {}),
+ mock.patch.object(cli, "SETTINGS_ERROR", None)):
+ target.start()
+ self.addCleanup(target.stop)
+
+ def _run(self, argv):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = cli.main(argv)
+ return code, output.getvalue()
+
+ def _count(self):
+ connection = sqlite3.connect(self.db)
+ try:
+ return connection.execute("SELECT COUNT(*) FROM asset").fetchone()[0]
+ finally:
+ connection.close()
+
+ def test_root_defaults_to_the_declared_root(self):
+ code, output = self._run(["scan", "local", "--db", str(self.db)])
+ self.assertEqual(code, 0)
+ self.assertIn("✓ local: 2 文件", output)
+ self.assertEqual(self._count(), 2)
+
+ def test_an_explicit_subdirectory_is_scanned_alone(self):
+ code, _ = self._run(["scan", "local", str(self.media / "sub"), "--db", str(self.db)])
+ self.assertEqual(code, 0)
+ self.assertEqual(self._count(), 1)
+
+ def test_an_undeclared_source_is_refused_and_lists_the_known_ones(self):
+ with self.assertRaises(SystemExit) as caught:
+ self._run(["scan", "nas", "--db", str(self.db)])
+ self.assertIn("nas", str(caught.exception))
+ self.assertIn("local", str(caught.exception))
+ self.assertEqual(self._count(), 0)
+
+ def test_a_missing_ledger_points_at_init(self):
+ code, output = self._run(["scan", "local", "--db", str(self.root / "nope.db")])
+ self.assertEqual(code, 4)
+ self.assertIn("peach init", output)
+
+
class ReplicationAssemblyTests(unittest.TestCase):
"""ADR-0023 第 3 阶段:整条复制链路按 `replication.enabled` 装配或完全不装配。"""
diff --git a/tests/test_config.py b/tests/test_config.py
index 45ceedec5..cd2b764a0 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -234,6 +234,19 @@ class BadFileTests(unittest.TestCase):
self.assertEqual(loaded.locations["nas"], "N:/")
self.assertEqual(loaded.mounts, {"nas": "/mnt/nas"})
+ def test_a_declared_locations_table_is_authoritative(self):
+ """`peach init` 的问答只声明 local;内建默认的示例盘符不得从旁边混进来。"""
+ with TempTree() as tree:
+ tree.write("[media.locations]\nlocal = 'D:\\Videos'\n")
+ loaded = tree.load()
+ self.assertEqual(loaded.locations, {"local": r"D:\Videos"})
+
+ def test_without_a_locations_table_the_builtin_defaults_apply(self):
+ with TempTree() as tree:
+ tree.write("[server]\nport = 9100\n")
+ loaded = tree.load()
+ self.assertEqual(loaded.locations, settings_file.DEFAULT_LOCATION_ROOTS)
+
def test_lenient_load_falls_back_to_builtin_defaults(self):
"""坏文件不能让进程连数据根都不知道——发现顺序不看文件内容。"""
with TempTree() as tree:
diff --git a/tests/test_onboarding.py b/tests/test_onboarding.py
new file mode 100644
index 000000000..da980b8d5
--- /dev/null
+++ b/tests/test_onboarding.py
@@ -0,0 +1,208 @@
+"""`peach.onboarding`:首次运行问答的题目、校验与落盘,纯逻辑、可注入。
+
+CLI 与将来的托盘设置页共用这一层,所以这里只用脚本化答案驱动,不碰 stdin;平台用
+`windows=` 注入,不看测试机自己是什么系统。
+"""
+from __future__ import annotations
+
+import io
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from peach import onboarding, settings_file
+
+
+def scripted(*answers: str):
+ """按顺序吐答案,并把每一题的题目与默认值记下来。"""
+ queue = list(answers)
+ seen: list[tuple[str, str]] = []
+
+ def ask(prompt: str, default: str) -> str:
+ seen.append((prompt, default))
+ return queue.pop(0)
+
+ ask.seen = seen # type: ignore[attr-defined]
+ return ask
+
+
+class _Case(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name).resolve()
+ self.home = self.root / "home"
+ self.home.mkdir()
+ self.media = self.root / "media"
+ self.media.mkdir()
+ self.config = settings_file.load_config(
+ project_root=self.root / "app", environ={"PEACH_DATA_ROOT": str(self.root / "peach-data")})
+
+
+class QuestionTests(_Case):
+ def test_questions_come_in_a_fixed_order_with_defaults_from_the_config(self):
+ asked = onboarding.questions(self.config, windows=True, home=self.home)
+ self.assertEqual([q.key for q in asked],
+ ["data_root", "media_dir", "host", "port", "mdns_name"])
+ by_key = {q.key: q for q in asked}
+ self.assertEqual(by_key["data_root"].default, str(self.root / "peach-data"))
+ self.assertEqual(by_key["host"].default, "1")
+ self.assertEqual(by_key["port"].default, "8900")
+ self.assertEqual(by_key["mdns_name"].default, "peach")
+
+ def test_media_default_is_the_system_video_folder_only_when_it_exists(self):
+ self.assertIsNone(onboarding.default_media_dir(self.home, windows=True))
+ (self.home / "Videos").mkdir()
+ self.assertEqual(onboarding.default_media_dir(self.home, windows=True),
+ self.home / "Videos")
+ self.assertIsNone(onboarding.default_media_dir(self.home, windows=False))
+ (self.home / "Movies").mkdir()
+ self.assertEqual(onboarding.default_media_dir(self.home, windows=False),
+ self.home / "Movies")
+ asked = {q.key: q for q in onboarding.questions(self.config, windows=False, home=self.home)}
+ self.assertEqual(asked["media_dir"].default, str(self.home / "Movies"))
+
+
+class ValidatorTests(_Case):
+ def test_media_dir_must_already_exist_and_is_never_created(self):
+ validate = onboarding.media_dir_validator(windows=False)
+ missing = self.root / "nope"
+ with self.assertRaises(ValueError) as caught:
+ validate(str(missing))
+ self.assertIn("不存在", str(caught.exception))
+ self.assertFalse(missing.exists())
+ with self.assertRaises(ValueError):
+ validate("")
+ self.assertEqual(validate(str(self.media)), self.media)
+
+ def test_host_accepts_the_two_choices_in_several_spellings(self):
+ for raw in ("1", "本机", "127.0.0.1"):
+ self.assertEqual(onboarding.validate_host(raw), "127.0.0.1")
+ for raw in ("2", "局域网", "0.0.0.0"):
+ self.assertEqual(onboarding.validate_host(raw), "0.0.0.0")
+ with self.assertRaises(ValueError):
+ onboarding.validate_host("3")
+
+ def test_port_is_an_integer_in_range(self):
+ self.assertEqual(onboarding.validate_port(" 8900 "), 8900)
+ for raw in ("0", "65536", "abc", ""):
+ with self.assertRaises(ValueError):
+ onboarding.validate_port(raw)
+
+ def test_mdns_name_is_a_dns_label(self):
+ self.assertEqual(onboarding.validate_mdns_name("peach-two"), "peach-two")
+ for raw in ("", "-peach", "peach.local", "pea ch"):
+ with self.assertRaises(ValueError):
+ onboarding.validate_mdns_name(raw)
+
+ def test_yes_no_defaults_to_yes(self):
+ for raw in ("", "y", "Yes", "是"):
+ self.assertTrue(onboarding.validate_yes_no(raw))
+ for raw in ("n", "NO", "否"):
+ self.assertFalse(onboarding.validate_yes_no(raw))
+ with self.assertRaises(ValueError):
+ onboarding.validate_yes_no("maybe")
+
+ def test_data_root_may_not_exist_yet_but_may_not_be_a_file(self):
+ self.assertEqual(onboarding.validate_data_root(str(self.root / "new")), self.root / "new")
+ (self.root / "file").write_text("x", encoding="utf-8")
+ with self.assertRaises(ValueError):
+ onboarding.validate_data_root(str(self.root / "file"))
+
+
+class AskUntilValidTests(_Case):
+ def test_empty_input_takes_the_default(self):
+ question = onboarding.Question("port", "服务端口", "8900", onboarding.validate_port)
+ self.assertEqual(onboarding.ask_until_valid(question, scripted(""), report=lambda _: None), 8900)
+
+ def test_invalid_answers_are_reported_and_reasked_up_to_the_limit(self):
+ question = onboarding.Question("port", "服务端口", "8900", onboarding.validate_port)
+ reported: list[str] = []
+ value = onboarding.ask_until_valid(question, scripted("x", "y", "9000"), report=reported.append)
+ self.assertEqual(value, 9000)
+ self.assertEqual(len(reported), 2)
+ self.assertIn("还可以再试 2 次", reported[0])
+ with self.assertRaises(onboarding.OnboardingAborted) as caught:
+ onboarding.ask_until_valid(question, scripted("x", "y", "z"), report=lambda _: None)
+ self.assertIn("服务端口", str(caught.exception))
+ self.assertIn("3 次", str(caught.exception))
+
+
+class ConfigureTests(_Case):
+ def _answers(self, **overrides):
+ base = dict(data_root=self.root / "peach-data", media_dir=self.media,
+ host="127.0.0.1", port=8900, mdns_name="peach")
+ base.update(overrides)
+ return onboarding.Answers(**base)
+
+ def test_windows_declares_the_directory_itself_and_leaves_mounts_empty(self):
+ prepared = onboarding.configure(self.config, self._answers(), windows=True)
+ self.assertEqual(prepared.locations, {"local": str(self.media)})
+ self.assertEqual(prepared.mounts, {})
+ self.assertEqual(onboarding.scan_root(prepared), str(self.media))
+
+ def test_posix_keeps_the_ledger_shape_and_mounts_the_directory(self):
+ prepared = onboarding.configure(self.config, self._answers(), windows=False)
+ self.assertEqual(prepared.locations, {"local": r"R:\media"})
+ self.assertEqual(prepared.mounts, {"local": str(self.media)})
+ self.assertEqual(onboarding.scan_root(prepared), r"R:\media")
+ self.assertIn(str(self.media), onboarding.mounts_explanation(self.media))
+
+ def test_only_the_asked_settings_change_and_replication_stays_off(self):
+ prepared = onboarding.configure(
+ self.config, self._answers(host="0.0.0.0", port=9443, mdns_name="peach-two"), windows=True)
+ self.assertEqual((prepared.server.host, prepared.server.port, prepared.server.mdns_name),
+ ("0.0.0.0", 9443, "peach-two"))
+ self.assertFalse(prepared.replication.enabled)
+ self.assertEqual(prepared.server.review_writer_origin, "")
+ self.assertEqual(prepared.replication.smb_host, "")
+ self.assertEqual(set(prepared.directories), set(settings_file.DIRECTORY_KEYS))
+
+ def test_the_written_file_reads_back_with_only_the_declared_source(self):
+ """`[media.locations]` 里只有 local:内建默认的示例盘符不得从旁边混进来。"""
+ prepared = onboarding.configure(self.config, self._answers(), windows=True)
+ settings_file.write(prepared)
+ loaded = settings_file.load_config(
+ project_root=self.root / "app", environ={"PEACH_DATA_ROOT": str(self.root / "peach-data")})
+ self.assertTrue(loaded.present)
+ self.assertEqual(loaded.locations, {"local": str(self.media)})
+ self.assertEqual(loaded.mounts, {})
+ self.assertFalse(loaded.replication.enabled)
+
+
+class InterviewTests(_Case):
+ def test_scripted_answers_drive_the_whole_interview(self):
+ ask = scripted("", str(self.media), "2", "", "peach-two")
+ answers = onboarding.interview(self.config, ask, windows=True, home=self.home,
+ report=lambda _: None)
+ self.assertEqual(answers, onboarding.Answers(
+ data_root=self.root / "peach-data", media_dir=self.media, host="0.0.0.0",
+ port=8900, mdns_name="peach-two"))
+ self.assertEqual([prompt for prompt, _ in ask.seen], [
+ "数据根(账本、缓存与设置文件都放这里)",
+ "本地媒体目录(来源 local,必须已存在)",
+ "监听范围:1 = 仅本机(127.0.0.1),2 = 局域网(0.0.0.0)",
+ "服务端口",
+ "局域网名字(<名字>.local,只在监听局域网时发布)",
+ ])
+
+ def test_console_ask_shows_the_default_and_treats_eof_as_abort(self):
+ with mock.patch("builtins.input", return_value="x") as prompt:
+ self.assertEqual(onboarding.console_ask("服务端口", "8900"), "x")
+ prompt.assert_called_once_with("服务端口 [8900]: ")
+ with mock.patch("builtins.input", return_value="") as prompt:
+ onboarding.console_ask("本地媒体目录", "")
+ prompt.assert_called_once_with("本地媒体目录(必填): ")
+ with mock.patch("builtins.input", side_effect=EOFError):
+ with self.assertRaises(onboarding.OnboardingAborted):
+ onboarding.console_ask("服务端口", "8900")
+
+ def test_only_a_real_terminal_counts_as_interactive(self):
+ self.assertFalse(onboarding.is_interactive(io.StringIO()))
+ self.assertFalse(onboarding.is_interactive(None))
+ self.assertTrue(onboarding.is_interactive(mock.Mock(isatty=lambda: True)))
+
+
+if __name__ == "__main__":
+ unittest.main()