fix(archive): 目标目录不可写时提前中止并提示 chown

This commit is contained in:
ali
2026-11-20 21:09:58 +08:00
parent e5b150b08e
commit 16d5c3a27c
+56 -2
View File
@@ -17,11 +17,15 @@
· 同名且大小相同 → 视为重复下载,跳过
· 同名但大小不同,或同集号(SxxEyy)已存在不同文件 → 冲突,跳过并留在源目录
需要旧的「目标存在就报错」行为时加 --no-merge。
目标目录不可写(例如 Jellyfin 以 root 保存元数据时创建的目录)会在移动前中止,
并给出 chown 命令,避免半途失败留下部分已移动文件。
"""
from __future__ import annotations
import argparse
import configparser
import errno
import json
import os
import re
@@ -223,11 +227,55 @@ def resolve_category(root: Path, raw: str, cats: list[str]) -> str | None:
# --------------------------------------------------------------------- 动作
def _owner_hint() -> str:
"""当前用户的 user:group,用于拼出可直接复制的 chown 命令。"""
try:
import grp
import pwd
ent = pwd.getpwuid(os.getuid())
group = grp.getgrgid(os.getgid()).gr_name
return f"{ent.pw_name}:{group}"
except (ImportError, KeyError):
return f"{os.getuid()}:{os.getgid()}"
def unwritable_targets(dest: Path, rels: list[Path] | None) -> list[Path]:
"""返回落点中当前用户不可写的目录(去重保序)。
rels=None 表示整目录移动,只检查 dest 的父目录;否则按新增文件逐个
向上找最近的已存在父目录。Jellyfin 以 root 保存元数据时会创建 root
目录,普通用户无法写入,移动会半路 PermissionError 并留下已移动的部分
文件,所以执行前先统一预检。
"""
parents = [dest.parent] if rels is None else [(dest / rel).parent for rel in rels]
bad: list[Path] = []
for parent in parents:
probe = parent
while not probe.exists() and probe != probe.parent and probe != dest.parent:
probe = probe.parent
if probe.exists() and not os.access(probe, os.W_OK | os.X_OK) and probe not in bad:
bad.append(probe)
return bad
def report_unwritable(bad: list[Path]) -> None:
quoted = " ".join(f'"{p}"' for p in bad)
die(
"目标目录不可写,已中止(未移动任何文件):\n"
+ "\n".join(f" - {p}" for p in bad)
+ "\n 常见原因:Jellyfin 以 root 保存元数据时创建了目录。"
+ f"\n 修复:sudo chown -R {_owner_hint()} {quoted}"
)
def move_to(src: Path, dest: Path) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
try:
os.rename(src, dest)
except OSError:
except OSError as exc:
if exc.errno != errno.EXDEV:
raise
shutil.move(str(src), str(dest))
@@ -299,7 +347,9 @@ def merge_into(src: Path, dest: Path) -> dict:
target.parent.mkdir(parents=True, exist_ok=True)
try:
os.rename(path, target)
except OSError:
except OSError as exc:
if exc.errno != errno.EXDEV:
raise
shutil.move(str(path), str(target))
moved += 1
try:
@@ -460,6 +510,10 @@ def main() -> int:
print("(dry-run,未执行移动)")
return 0
bad_targets = unwritable_targets(dest, merge_plan["new"] if merging else None)
if bad_targets:
report_unwritable(bad_targets)
if not args.yes:
try:
confirm = unicodedata.normalize("NFKC", input("确认归档?[Y/n]: ")).strip().lower()