Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(tooling): 同步整理目录字幕路径并恢复部分失败移动

longmeidao6435a3d14c3d
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 9f940736f..1e5d2c779 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -189,6 +189,14 @@ JAV 默认封面(官方封面/预览图)与视频默认大小(大图/
| `jobs.PidFileLock` 批处理进程锁 | `portalocker==4.3.0` | 候选覆盖 PID 写入、持有者、原子替换与陈旧文件清理,但一直没有消费者落地;按「候选依赖不得空转」不引入。 |
| `record_rehome.py` 个人记录接回新文件 | 按文件指纹接回;六张表改 `ON DELETE SET NULL` | 消失的文件读不到、算不出指纹;记录脱离 `asset` 就丢了番号与标题。番号是唯一跨版本稳定的键,无番号的按创作者、文件名主干与时长接回(ADR-0087)。 |
+发行物目录折叠与目录广告清理复用 `scripts/flatten_release_dirs.py`、`catalog_rules` 和 SQLite 备份。
+路径计划按目录组件建索引并保留操作顺序,覆盖资产及已登记字幕;物理移动携带未登记封面等旁挂文件。
+目录图排除文件末层;同名的多个子目录及带媒体扩展名的目录包装按冗余层判定,扩展名复用扫描器分类。
+冗余目录独占父目录时使用两次整目录改名及空暂存目录清理;父目录含附带文件或其他版本时,目标条目互不冲突才合并。暂存位置或文件名冲突时拒绝执行。
+包装目录占用内容目标名时,先暂存该目录再移出内容,其他版本保留原位。
+每条移动先复验真实目录,部分失败立即恢复本条,账本事务失败恢复本批。
+不新增依赖;Python 标准库的路径操作和 SQLite 已覆盖底层能力,Peach 保留冗余名称、广告和账本一致性判据。
+
保留自研不是永久豁免:约束改变或候选实现更新时重新跑 POC,不因本表结论跳过外部检索。
## 已定型的产品行为
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 9bf0bed1b..a4e7b6ad8 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -21,7 +21,7 @@
- 访问密码未开,局域网匿名可读;可选密码首启可跳过,配置页可改可关,登录可记住设备。
- macOS 是 reader,代码与 `peach-data` 在内置盘;`peach.local` 经 8900/8443 和 pf 提供 80/443,GET 正常、写入回 409。
- 两端各用本机 CA,私钥与凭据不跨机;代码走 Git、账本单写者复制、图片走 Syncthing;本机坐标见 `<数据根>/config.toml`。
-- Windows ledger `peach-data/database/ledger.db`,2026-10-06 `0044`;`asset_subtitle` 195 行(孤立 19),175 部带字幕轨,`asset` 80,356 行。
+- Windows ledger `0045`(2026-10-07);`asset_subtitle` 195 行(孤立 19),175 部带字幕轨,`asset` 80,202 行。
- Mac ledger 经授权从共享副本拉取,恢复 `in-sync`;`sources` 在内置盘,`archive`、`tools` 可指向外置盘。
- Windows doctor、诊断页通过 CA 核验;本地目录缺失,115/PikPak 可读取;密码未开、历史失败为警告。
- 本机 Python 3.14;`requires-python` 下限 3.12,CI 同测 3.12 与 3.14;Windows FFmpeg/ffprobe 在 `peach-data/tools/ffmpeg`,macOS 走 PATH。
diff --git a/scripts/flatten_release_dirs.py b/scripts/flatten_release_dirs.py
index 3a85cfb3b..99145f990 100644
--- a/scripts/flatten_release_dirs.py
+++ b/scripts/flatten_release_dirs.py
@@ -21,6 +21,7 @@ r"""摘掉发行物目录上多余的一层,并去掉目录名里的广告标
from __future__ import annotations
import argparse
+import hashlib
import sqlite3
import sys
from collections import defaultdict
@@ -39,11 +40,20 @@ from peach.config import DATABASE_PATH, GENERATED_DIR
from peach.migrations import sqlite_backup
from peach.platform import translate_ledger_path
from peach.review_csv import write_rows
+from peach.scan import medium_of
PLAN_FIELDS = ["kind", "ledger_dir", "target_dir", "assets", "verified"]
+def directory_key(name: str) -> str:
+ """目录同名判据包含媒体扩展名包装,文件本身不参与目录图。"""
+ cleaned = strip_promo_markers(name)
+ if medium_of(cleaned) != "other":
+ cleaned = PureWindowsPath(cleaned).stem
+ return promo_free_key(cleaned)
+
+
def _directories(connection: sqlite3.Connection) -> dict[str, set[str]]:
"""账本认识的目录树:目录 -> 直接子目录集合。
@@ -58,8 +68,10 @@ def _directories(connection: sqlite3.Connection) -> dict[str, set[str]]:
parts = PureWindowsPath(str(path)).parts
for index in range(1, len(parts) - 1):
parent = str(PureWindowsPath(*parts[:index + 1]))
- child = str(PureWindowsPath(*parts[:index + 2]))
- children[parent].add(child)
+ children.setdefault(parent, set())
+ if index < len(parts) - 2:
+ child = str(PureWindowsPath(*parts[:index + 2]))
+ children[parent].add(child)
return children
@@ -74,20 +86,16 @@ def plan_operations(connection: sqlite3.Connection) -> list[dict[str, str]]:
collapsed: set[str] = set()
operations: list[dict[str, str]] = []
for parent in sorted(children):
- kids = children[parent]
- if len(kids) != 1:
- continue
- child = next(iter(kids))
- child_name = PureWindowsPath(child).name
parent_name = PureWindowsPath(parent).name
- key = promo_free_key(child_name)
- if not key or key != promo_free_key(parent_name):
- continue
- collapsed.add(child)
- operations.append({
- "kind": "collapse", "ledger_dir": child, "target_dir": parent,
- "assets": str(counts.get(child, 0)), "verified": "",
- })
+ for child in sorted(children[parent]):
+ key = directory_key(PureWindowsPath(child).name)
+ if not key or key != directory_key(parent_name):
+ continue
+ collapsed.add(child)
+ operations.append({
+ "kind": "collapse", "ledger_dir": child, "target_dir": parent,
+ "assets": str(counts.get(child, 0)), "verified": "",
+ })
for directory in sorted(set(children) | {c for kids in children.values() for c in kids}):
if directory in collapsed:
continue
@@ -111,7 +119,7 @@ def _asset_counts(connection: sqlite3.Connection) -> dict[str, int]:
"SELECT path FROM asset WHERE path IS NOT NULL AND trim(path)<>''"
):
parts = PureWindowsPath(str(path)).parts
- for index in range(1, len(parts)):
+ for index in range(1, len(parts) - 1):
counts[str(PureWindowsPath(*parts[:index + 1]))] += 1
return counts
@@ -119,8 +127,7 @@ def _asset_counts(connection: sqlite3.Connection) -> dict[str, int]:
def verify(operation: dict[str, str], resolve=translate_ledger_path) -> str:
"""用真实文件系统核一条计划,返回 `ok` 或拒绝原因。
- 账本不知道旁挂文件,所以 collapse 前必须确认父目录里除了这个子目录真的什么都没有;
- 只按账本判会把父目录里的封面、字幕留在原地,或者在提升时撞名。
+ 冗余层只在目标条目互不冲突时合并,父目录的封面与字幕保留。
"""
source = resolve(operation["ledger_dir"])
target = resolve(operation["target_dir"])
@@ -133,7 +140,12 @@ def verify(operation: dict[str, str], resolve=translate_ledger_path) -> str:
return f"跳过:父目录读不到({error.__class__.__name__})"
extra = [name for name in siblings if name != source.name]
if extra:
- return f"跳过:父目录还有 {len(extra)} 项({extra[0]})"
+ try:
+ for entry in source.iterdir():
+ if entry.name.casefold() != source.name.casefold() and (target / entry.name).exists():
+ return f"跳过:目标条目已存在({entry.name})"
+ except OSError as error:
+ return f"跳过:子目录读不到({error.__class__.__name__})"
return "ok"
if target.exists():
return "跳过:目标名已存在"
@@ -153,14 +165,27 @@ def _rewrite(path: str, operation: dict[str, str]) -> str | None:
def plan_paths(connection: sqlite3.Connection,
- operations: list[dict[str, str]]) -> list[dict[str, str]]:
+ operations: list[dict[str, str]], *, table: str = "asset") -> list[dict[str, str]]:
"""按操作顺序(深的在前)逐条改写账本路径,返回真正会变的行。"""
+ if table not in {"asset", "asset_subtitle"}:
+ raise ValueError("路径表不受支持")
+ indexed: dict[tuple[str, ...], list[tuple[int, dict[str, str]]]] = defaultdict(list)
+ for index, operation in enumerate(operations):
+ key = tuple(part.casefold() for part in PureWindowsPath(operation["ledger_dir"]).parts)
+ indexed[key].append((index, operation))
rows: list[dict[str, str]] = []
for asset_id, path in connection.execute(
- "SELECT id,path FROM asset WHERE path IS NOT NULL AND trim(path)<>'' ORDER BY id"
+ f"SELECT id,path FROM {table} WHERE path IS NOT NULL AND trim(path)<>'' ORDER BY id"
):
current = str(path)
- for operation in operations:
+ cursor = -1
+ for _ in range(len(operations)):
+ parts = tuple(part.casefold() for part in PureWindowsPath(current).parts)
+ matches = [item for depth in range(1, len(parts))
+ for item in indexed.get(parts[:depth], ()) if item[0] > cursor]
+ if not matches:
+ break
+ cursor, operation = min(matches, key=lambda item: item[0])
rewritten = _rewrite(current, operation)
if rewritten is not None:
current = rewritten
@@ -173,28 +198,76 @@ def apply_operation(operation: dict[str, str], resolve=translate_ledger_path) ->
"""执行一条操作,返回已完成的移动,用于回滚。"""
source = resolve(operation["ledger_dir"])
target = resolve(operation["target_dir"])
+ if source.is_symlink() or target.is_symlink():
+ raise ValueError("拒绝符号链接目录")
+ verification = verify(operation, resolve)
+ if verification != "ok":
+ raise ValueError(verification)
if operation["kind"] == "rename":
source.rename(target)
return [(source, target)]
done: list[tuple[Path, Path]] = []
- for entry in sorted(source.iterdir()):
- moved = target / entry.name
- entry.rename(moved)
- done.append((entry, moved))
- source.rmdir()
- done.append((source, source)) # 记一笔,回滚时重建这个目录
+ if any(entry.name != source.name for entry in target.iterdir()):
+ entries = list(source.iterdir())
+ if any(entry.name.casefold() != source.name.casefold() and (target / entry.name).exists()
+ for entry in entries):
+ raise FileExistsError("目标条目已存在")
+ move_root = source
+ try:
+ if any(entry.name.casefold() == source.name.casefold() for entry in entries):
+ digest = hashlib.sha256(operation["ledger_dir"].encode("utf-8")).hexdigest()[:20]
+ move_root = source.with_name(".peach-organize-" + digest)
+ if move_root.exists() or move_root.is_symlink():
+ raise FileExistsError("目录暂存位置已存在")
+ source.rename(move_root)
+ done.append((source, move_root))
+ for entry in entries:
+ entry = move_root / entry.name
+ destination = target / entry.name
+ entry.rename(destination)
+ done.append((entry, destination))
+ done.append((move_root, move_root))
+ try:
+ move_root.rmdir()
+ except FileNotFoundError:
+ pass
+ except Exception:
+ rollback(done)
+ raise
+ return done
+ digest = hashlib.sha256(operation["ledger_dir"].encode("utf-8")).hexdigest()[:20]
+ staging = target.with_name(".peach-organize-" + digest)
+ if staging.exists() or staging.is_symlink():
+ raise FileExistsError("目录暂存位置已存在")
+ staged_child = staging / source.name
+ try:
+ target.rename(staging)
+ done.append((target, staging))
+ staged_child.rename(target)
+ done.append((staged_child, target))
+ done.append((staging, staging))
+ try:
+ staging.rmdir()
+ except FileNotFoundError:
+ pass
+ except Exception:
+ rollback(done)
+ raise
return done
def rollback(done: list[tuple[Path, Path]]) -> None:
+ failures = []
for source, target in reversed(done):
try:
if source == target:
source.mkdir(exist_ok=True)
else:
target.rename(source)
- except OSError:
- print(f" 回滚失败,需要人工处理:{target} -> {source}")
+ except OSError as error:
+ failures.append(f"{target} -> {source}: {error}")
+ if failures:
+ raise RuntimeError("文件恢复失败:" + ";".join(failures))
def build_parser() -> argparse.ArgumentParser:
@@ -211,6 +284,34 @@ def build_parser() -> argparse.ArgumentParser:
return parser
+def apply_plan(connection: sqlite3.Connection, operations: list[dict[str, str]],
+ rows: list[dict[str, str]], subtitle_rows: list[dict[str, str]]) -> None:
+ """在写锁内复验路径、移动目录与引用;失败恢复账本及文件。"""
+ baseline_fk = set(connection.execute("PRAGMA foreign_key_check"))
+ done: list[tuple[Path, Path]] = []
+ try:
+ connection.execute("BEGIN IMMEDIATE")
+ if (plan_paths(connection, operations) != rows or
+ plan_paths(connection, operations, table="asset_subtitle") != subtitle_rows):
+ raise ValueError("冻结路径计划已失效")
+ for operation in operations:
+ done.extend(apply_operation(operation))
+ for table, changes in (("asset", rows), ("asset_subtitle", subtitle_rows)):
+ for row in changes:
+ changed = connection.execute(
+ f"UPDATE {table} SET path=? WHERE id=? AND path=?",
+ (row["new_path"], int(row["id"]), row["old_path"])).rowcount
+ if changed != 1:
+ raise ValueError("账本路径更新失败")
+ if set(connection.execute("PRAGMA foreign_key_check")) - baseline_fk:
+ raise ValueError("出现新增外键问题")
+ connection.commit()
+ except Exception:
+ connection.rollback()
+ rollback(done)
+ raise
+
+
def run(args: argparse.Namespace) -> int:
if args.apply and not args.backup:
raise SystemExit("--apply 必须同时给 --backup")
@@ -224,13 +325,17 @@ def run(args: argparse.Namespace) -> int:
write_rows(args.plan_csv, PLAN_FIELDS, operations)
ready = [row for row in operations if row["verified"] == "ok"]
rows = plan_paths(connection, ready)
+ subtitle_rows = plan_paths(connection, ready, table="asset_subtitle")
write_rows(args.path_csv, ["id", "old_path", "new_path"], rows)
+ write_rows(args.path_csv.with_name(args.path_csv.stem + "-subtitles.csv"),
+ ["id", "old_path", "new_path"], subtitle_rows)
collapses = sum(1 for row in ready if row["kind"] == "collapse")
print(f"计划 {len(operations)} 条,可执行 {len(ready)} 条"
f"(collapse {collapses},rename {len(ready) - collapses}),"
- f"影响账本路径 {len(rows)} 条")
+ f"影响资产路径 {len(rows)} 条、字幕路径 {len(subtitle_rows)} 条")
print(f" 计划 CSV:{args.plan_csv}")
print(f" 路径 CSV:{args.path_csv}")
+ print(f" 字幕 CSV:{args.path_csv.with_name(args.path_csv.stem + '-subtitles.csv')}")
# 逐条打印被跳过的路径会在 GBK 控制台上崩掉(媒体名里有 emoji 和生僻字),
# 而且量级是四位数。原因按类归并打印,明细留在计划 CSV 里。
skipped: dict[str, int] = defaultdict(int)
@@ -250,19 +355,7 @@ def run(args: argparse.Namespace) -> int:
sqlite_backup(args.db, args.backup)
print(f" 已备份到 {args.backup}")
- done: list[tuple[Path, Path]] = []
- try:
- for operation in ready:
- done.extend(apply_operation(operation))
- with connection:
- for row in rows:
- connection.execute(
- "UPDATE asset SET path=? WHERE id=? AND path=?",
- (row["new_path"], int(row["id"]), row["old_path"]))
- except Exception:
- print(" 执行失败,回滚已完成的移动")
- rollback(done)
- raise
+ apply_plan(connection, ready, rows, subtitle_rows)
after = connection.execute("SELECT count(*) FROM asset").fetchone()[0]
print(f" 已执行 {len(ready)} 条;资产 {before} -> {after}")
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index a501e2ac9..8ea453c3b 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -2702,6 +2702,235 @@ class FlattenReleaseDirTests(unittest.TestCase):
def _resolver(self, root: Path):
return lambda ledger: root.joinpath(*PureWindowsPath(str(ledger)).parts[1:])
+ def test_path_index_preserves_operation_order_and_component_boundaries(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ connection = self._ledger(Path(tmp).resolve(), [
+ r"B:\old\inner\a.mp4", r"B:\old-other\b.mp4", r"B:\OLD\c.mp4"])
+ operations = [
+ {"ledger_dir": r"B:\old\inner", "target_dir": r"B:\old\renamed"},
+ {"ledger_dir": r"B:\old", "target_dir": r"B:\new"},
+ {"ledger_dir": r"B:\new\renamed", "target_dir": r"B:\final"}]
+ self.assertEqual(self.flatten.plan_paths(connection, operations), [
+ {"id": "1", "old_path": r"B:\old\inner\a.mp4", "new_path": r"B:\final\a.mp4"},
+ {"id": "3", "old_path": r"B:\OLD\c.mp4", "new_path": r"B:\new\c.mp4"}])
+ connection.close()
+
+ def test_directory_plan_excludes_files_and_includes_redundant_siblings(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ connection = self._ledger(Path(tmp).resolve(), [
+ r"B:\ABC-123\ABC-123.mp4",
+ r"B:\ATID-353\ATID-353.mp4\ATID-353.mp4",
+ r"B:\BAZX-123\[Thz.la]bazx-123\BAZX-123cd1.mp4",
+ r"B:\BAZX-123\bazx-123\BAZX-123.mp4",
+ r"B:\合集\XYZ-456\XYZ-456.mp4"])
+ operations = self.flatten.plan_operations(connection)
+ self.assertEqual({op["ledger_dir"] for op in operations}, {
+ r"B:\ATID-353\ATID-353.mp4",
+ r"B:\BAZX-123\[Thz.la]bazx-123",
+ r"B:\BAZX-123\bazx-123"})
+ self.assertTrue(all(op["kind"] == "collapse" and op["assets"] == "1"
+ for op in operations))
+ self.assertEqual(len(self.flatten.plan_paths(connection, operations)), 3)
+ connection.close()
+
+ def test_shared_parent_keeps_sidecars_and_recovers_directory_contents(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = root / "same" / "same"
+ source.mkdir(parents=True)
+ (source.parent / "poster.jpg").write_bytes(b"cover")
+ (source / "a.mp4").write_bytes(b"media")
+ (source / "b.srt").write_bytes(b"subtitle")
+ operation = {"kind": "collapse", "ledger_dir": r"B:\same\same", "target_dir": r"B:\same"}
+ done = self.flatten.apply_operation(operation, self._resolver(root))
+ self.assertFalse(source.exists())
+ self.assertEqual((source.parent / "poster.jpg").read_bytes(), b"cover")
+ self.assertEqual((source.parent / "a.mp4").read_bytes(), b"media")
+ self.flatten.rollback(done)
+ rename, attempts = Path.rename, [0]
+ def fail_second_move(path, target):
+ attempts[0] += 1
+ if attempts[0] == 2:
+ raise OSError("blocked file move")
+ return rename(path, target)
+ with mock.patch.object(Path, "rename", fail_second_move):
+ with self.assertRaisesRegex(OSError, "blocked file move"):
+ self.flatten.apply_operation(operation, self._resolver(root))
+ self.assertEqual((source / "a.mp4").read_bytes(), b"media")
+ self.assertEqual((source / "b.srt").read_bytes(), b"subtitle")
+ self.assertEqual((source.parent / "poster.jpg").read_bytes(), b"cover")
+
+ def test_directory_plan_cleans_advertised_leaf_directory(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ connection = self._ledger(Path(tmp).resolve(), [
+ r"B:\[Thz.la]ABC-123\[Thz.la]ABC-123.mp4"])
+ self.assertEqual(self.flatten.plan_operations(connection), [{
+ "kind": "rename", "ledger_dir": r"B:\[Thz.la]ABC-123",
+ "target_dir": r"B:\ABC-123", "assets": "1", "verified": ""}])
+ connection.close()
+
+ def test_shared_parent_collision_keeps_both_files(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = root / "same" / "same"
+ source.mkdir(parents=True)
+ (source.parent / "a.mp4").write_bytes(b"parent version")
+ (source / "a.mp4").write_bytes(b"child version")
+ operation = {"kind": "collapse", "ledger_dir": r"B:\same\same", "target_dir": r"B:\same"}
+ with self.assertRaisesRegex(ValueError, "目标条目已存在"):
+ self.flatten.apply_operation(operation, self._resolver(root))
+ self.assertEqual((source.parent / "a.mp4").read_bytes(), b"parent version")
+ self.assertEqual((source / "a.mp4").read_bytes(), b"child version")
+
+ def test_media_wrapper_with_siblings_preserves_versions_and_recovers(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = root / "VGD-157" / "VGD-157.mp4"
+ source.mkdir(parents=True)
+ (source.parent / "VGD-157.mkv").write_bytes(b"other version")
+ (source / "VGD-157.mp4").write_bytes(b"media")
+ (source / "VGD-157.srt").write_bytes(b"subtitle")
+ operation = {"kind": "collapse", "ledger_dir": r"B:\VGD-157\VGD-157.mp4",
+ "target_dir": r"B:\VGD-157"}
+ resolver = self._resolver(root)
+ done = self.flatten.apply_operation(operation, resolver)
+ self.assertTrue(source.is_file())
+ self.assertEqual(source.read_bytes(), b"media")
+ self.assertEqual((source.parent / "VGD-157.mkv").read_bytes(), b"other version")
+ self.flatten.rollback(done)
+ rename = Path.rename
+ for failing_step in (1, 2, 3):
+ attempts = [0]
+ def fail_move(path, target, attempts=attempts, failing_step=failing_step):
+ attempts[0] += 1
+ if attempts[0] == failing_step:
+ raise OSError("blocked wrapper move")
+ return rename(path, target)
+ with mock.patch.object(Path, "rename", fail_move):
+ with self.assertRaisesRegex(OSError, "blocked wrapper move"):
+ self.flatten.apply_operation(operation, resolver)
+ self.assertEqual((source / "VGD-157.mp4").read_bytes(), b"media")
+ self.assertEqual((source / "VGD-157.srt").read_bytes(), b"subtitle")
+ self.assertEqual((source.parent / "VGD-157.mkv").read_bytes(), b"other version")
+ self.assertFalse(list(source.parent.glob(".peach-organize-*")))
+
+ def test_partial_directory_failure_restores_already_moved_entries(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = root / "same" / "same"
+ source.mkdir(parents=True)
+ (source / "a.mp4").write_bytes(b"media")
+ (source / "b.srt").write_bytes(b"subtitle")
+ rename = Path.rename
+ attempts = [0]
+ def fail_second_move(path, target):
+ attempts[0] += 1
+ if attempts[0] == 2:
+ raise OSError("blocked")
+ return rename(path, target)
+ operation = {"kind": "collapse", "ledger_dir": r"B:\same\same", "target_dir": r"B:\same"}
+ with mock.patch.object(Path, "rename", fail_second_move):
+ with self.assertRaisesRegex(OSError, "blocked"):
+ self.flatten.apply_operation(operation, self._resolver(root))
+ self.assertEqual((source / "a.mp4").read_bytes(), b"media")
+ self.assertEqual((source / "b.srt").read_bytes(), b"subtitle")
+ self.assertFalse((source.parent / "a.mp4").exists())
+
+ def test_apply_synchronises_registered_subtitles_and_carries_covers(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ inner = root / "TRE-080" / "TRE-080"
+ inner.mkdir(parents=True)
+ for name in ("TRE-080.mp4", "TRE-080.srt", "poster.jpg"):
+ (inner / name).write_bytes(name.encode())
+ connection = self._ledger(root, [r"B:\TRE-080\TRE-080\TRE-080.mp4"])
+ connection.execute("INSERT INTO asset_subtitle(asset_id,location,path,name,language,format,size,mtime,pairing,first_seen,last_seen) VALUES(1,'115',?,'TRE-080.srt','zh','srt',1,0,'exact','now','now')",
+ (r"B:\TRE-080\TRE-080\TRE-080.srt",))
+ connection.commit(); connection.close()
+ args = self.flatten.build_parser().parse_args([
+ "--db", str(root / "ledger.db"), "--plan-csv", str(root / "plan.csv"),
+ "--path-csv", str(root / "paths.csv"), "--apply", "--backup", str(root / "backup.db")])
+ verify, apply = self.flatten.verify, self.flatten.apply_operation
+ resolve = self._resolver(root)
+ rename = Path.rename
+ def directory_only(path, target):
+ if not path.is_dir():
+ raise OSError("file moves unsupported")
+ return rename(path, target)
+ with mock.patch.object(self.flatten, "verify", side_effect=lambda op, *args: verify(op, resolve)), \
+ mock.patch.object(self.flatten, "apply_operation", side_effect=lambda op: apply(op, resolve)), \
+ mock.patch.object(Path, "rename", directory_only):
+ self.assertEqual(self.flatten.run(args), 0)
+ connection = sqlite3.connect(root / "ledger.db")
+ self.assertEqual(connection.execute("SELECT path FROM asset_subtitle").fetchone()[0], r"B:\TRE-080\TRE-080.srt")
+ self.assertEqual(connection.execute("SELECT path FROM asset").fetchone()[0], r"B:\TRE-080\TRE-080.mp4")
+ self.assertEqual(connection.execute("PRAGMA integrity_check").fetchone()[0], "ok")
+ connection.close()
+ self.assertTrue((inner.parent / "poster.jpg").is_file())
+ self.assertTrue((root / "backup.db").is_file())
+
+ def test_directory_backend_can_remove_empty_staging_folder(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = root / "same" / "same"
+ source.mkdir(parents=True)
+ (source / "a.mp4").write_bytes(b"media")
+ operation = {"kind": "collapse", "ledger_dir": r"B:\same\same", "target_dir": r"B:\same"}
+ rename = Path.rename
+ def remove_empty_parent(path, target):
+ result = rename(path, target)
+ if path.parent.name.startswith(".peach-organize-"):
+ path.parent.rmdir()
+ return result
+ with mock.patch.object(Path, "rename", remove_empty_parent):
+ done = self.flatten.apply_operation(operation, self._resolver(root))
+ self.assertEqual((source.parent / "a.mp4").read_bytes(), b"media")
+ self.flatten.rollback(done)
+ self.assertEqual((source / "a.mp4").read_bytes(), b"media")
+
+ def test_staging_cleanup_failure_restores_the_original_directory(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = root / "same" / "same"
+ source.mkdir(parents=True)
+ (source / "a.mp4").write_bytes(b"media")
+ operation = {"kind": "collapse", "ledger_dir": r"B:\same\same", "target_dir": r"B:\same"}
+ remove = Path.rmdir
+ def fail_staging(path):
+ if path.name.startswith(".peach-organize-"):
+ raise OSError("blocked cleanup")
+ return remove(path)
+ with mock.patch.object(Path, "rmdir", fail_staging):
+ with self.assertRaisesRegex(OSError, "blocked cleanup"):
+ self.flatten.apply_operation(operation, self._resolver(root))
+ self.assertEqual((source / "a.mp4").read_bytes(), b"media")
+ self.assertEqual(list(root.iterdir()), [source.parent])
+
+ def test_subtitle_database_failure_restores_media_and_all_paths(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ source = root / "same" / "same"
+ source.mkdir(parents=True)
+ (source / "a.mp4").write_bytes(b"media")
+ (source / "a.srt").write_bytes(b"subtitle")
+ connection = self._ledger(root, [r"B:\same\same\a.mp4"])
+ connection.execute("INSERT INTO asset_subtitle(asset_id,location,path,name,format,pairing,first_seen,last_seen) VALUES(1,'115',?,'a.srt','srt','exact','now','now')",
+ (r"B:\same\same\a.srt",))
+ connection.execute("CREATE TRIGGER blocked_subtitle BEFORE UPDATE ON asset_subtitle BEGIN SELECT RAISE(ABORT,'blocked subtitle'); END")
+ connection.commit()
+ operation = {"kind": "collapse", "ledger_dir": r"B:\same\same", "target_dir": r"B:\same"}
+ rows = self.flatten.plan_paths(connection, [operation])
+ subs = self.flatten.plan_paths(connection, [operation], table="asset_subtitle")
+ apply = self.flatten.apply_operation
+ with mock.patch.object(self.flatten, "apply_operation", side_effect=lambda op: apply(op, self._resolver(root))):
+ with self.assertRaisesRegex(sqlite3.IntegrityError, "blocked subtitle"):
+ self.flatten.apply_plan(connection, [operation], rows, subs)
+ self.assertEqual(connection.execute("SELECT path FROM asset").fetchone()[0], r"B:\same\same\a.mp4")
+ self.assertEqual(connection.execute("SELECT path FROM asset_subtitle").fetchone()[0], r"B:\same\same\a.srt")
+ self.assertEqual((source / "a.mp4").read_bytes(), b"media")
+ self.assertEqual((source / "a.srt").read_bytes(), b"subtitle")
+ connection.close()
+
def test_collapse_needs_a_redundant_name_not_just_a_lone_child(self):
"""`古川结爱合集` 底下只有一个 `FC2-PPV-…` 也是有意义的一层,不能合。
@@ -2722,8 +2951,8 @@ class FlattenReleaseDirTests(unittest.TestCase):
self.assertNotIn(r"B:\日本\Prestige\TRE-080\[44x.me]tre-080", renames,
"已经被合掉的目录不该再排一次改名")
- def test_collapse_refuses_when_the_parent_holds_something_the_ledger_never_saw(self):
- """账本只记文件,不记字幕、封面和空目录;不核真实目录就会把它们留在原地。"""
+ def test_collapse_preserves_unregistered_parent_cover(self):
+ """父目录中未登记的封面随媒体合并保留原位。"""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
inner = root / "日本" / "TRE-080" / "[44x.me]tre-080"
@@ -2735,7 +2964,12 @@ class FlattenReleaseDirTests(unittest.TestCase):
resolve = self._resolver(root)
self.assertEqual(self.flatten.verify(operation, resolve), "ok")
(inner.parent / "cover.jpg").write_text("x", encoding="utf-8")
- self.assertTrue(self.flatten.verify(operation, resolve).startswith("跳过:父目录还有"))
+ self.assertEqual(self.flatten.verify(operation, resolve), "ok")
+ done = self.flatten.apply_operation(operation, resolve)
+ self.assertEqual((inner.parent / "cover.jpg").read_text(encoding="utf-8"), "x")
+ self.assertEqual((inner.parent / "TRE-080.mp4").read_text(encoding="utf-8"), "x")
+ self.flatten.rollback(done)
+ self.assertTrue((inner / "TRE-080.mp4").is_file())
def test_apply_moves_files_up_then_rewrites_the_ledger(self):
with tempfile.TemporaryDirectory() as tmp: