"""文件落盘的小工具。""" from __future__ import annotations import errno import os import shutil from pathlib import Path def link_or_copy(source: str | Path, destination: str | Path) -> str: """给文件建硬链接;跨文件系统时退回复制。返回 "hard" 或 "copy"。 硬链接不占额外磁盘,却表现得和真实文件一样——产出目录可以整个拷走。 数据集动辄上万张图,链接与复制的差别是几百 MB 起步。 """ destination = Path(destination) if destination.exists() or destination.is_symlink(): destination.unlink() destination.parent.mkdir(parents=True, exist_ok=True) try: os.link(source, destination) return "hard" except OSError as exc: if exc.errno != errno.EXDEV: raise shutil.copy2(source, destination) return "copy"