"""成果打包及文件操作。""" from pathlib import Path from time import sleep import re import shutil import zipfile from . import config def safe_filename(value): text = str(value or "").strip() text = re.sub(r'[<>:"/\\|?*\s]+', "_", text) text = text.strip("._") return text or "unnamed" def market_output_dir(output_dir, market): return output_dir / safe_filename(market.code) def market_zip_output_path(output_dir, market): return output_dir / f"{safe_filename(market.code)}.zip" def competitor_signal_raster_filename(): return config.COMPETITOR_SIGNAL_OUTPUT_FILENAME def zip_member_reference(zip_path, member_path): return f"{zip_path.as_posix()}/{member_path.as_posix()}" def rewrite_result_for_zip(result, zip_path, workspace_dir): rewritten = dict(result) rewritten.pop("market_dir", None) rewritten["zip_output"] = zip_path.as_posix() output = rewritten.get("output") if output: output_path = Path(output) try: member_path = output_path.resolve().relative_to(workspace_dir.resolve()) except ValueError: member_path = Path(output_path.name) rewritten["output"] = zip_member_reference(zip_path, member_path) return rewritten def write_market_zip(workspace_dir, zip_path, market): if zip_path.exists(): if not config.OVERWRITE: return { "market_code": market.code, "market_name": market.name, "output": zip_path.as_posix(), "skipped": True, } entries = sorted(path for path in workspace_dir.rglob("*") if path.is_file()) temp_zip_path = zip_path.with_name(f".{zip_path.name}.tmp") if temp_zip_path.exists(): temp_zip_path.unlink() try: with zipfile.ZipFile(temp_zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zip_file: for path in entries: zip_file.write(path, path.relative_to(workspace_dir).as_posix()) replace_file_with_retry(temp_zip_path, zip_path) except Exception: if temp_zip_path.exists(): temp_zip_path.unlink() raise return { "market_code": market.code, "market_name": market.name, "output": zip_path.as_posix(), "entries": [path.relative_to(workspace_dir).as_posix() for path in entries], "bytes": zip_path.stat().st_size, "skipped": False, } def remove_legacy_market_dir(output_dir, market): legacy_dir = market_output_dir(output_dir, market) if not legacy_dir.exists() or not legacy_dir.is_dir(): return None output_root = output_dir.resolve() target = legacy_dir.resolve() if output_root not in target.parents: raise ValueError(f"拒绝删除输出目录之外的路径:{target}") shutil.rmtree(target) return legacy_dir def replace_file_with_retry(source_path, target_path, attempts=20, delay_seconds=0.5): for attempt in range(attempts): try: source_path.replace(target_path) return except PermissionError: if attempt == attempts - 1: raise sleep(delay_seconds) def remove_file_with_retry(path, attempts=20, delay_seconds=0.5): for attempt in range(attempts): try: path.unlink(missing_ok=True) return except PermissionError: if attempt == attempts - 1: raise sleep(delay_seconds) def copy_full_source_file(source_path, output_path, market): if output_path.exists() and not config.OVERWRITE: return { "market_code": market.code, "market_name": market.name, "source": str(source_path), "output": str(output_path), "skipped": True, } shutil.copy2(source_path, output_path) return { "market_code": market.code, "market_name": market.name, "source": str(source_path), "output": str(output_path), "bytes": output_path.stat().st_size, "copied_full_source": True, "skipped": False, }