#!/usr/bin/env python3 """Сохранение файлов закладок браузеров в отдельный каталог.""" from __future__ import annotations import argparse import glob import hashlib import json import os import re import shutil import sys import time from pathlib import Path def file_digest(path: Path, chunk_size: int = 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while block := handle.read(chunk_size): digest.update(block) return digest.hexdigest() def default_patterns() -> list[str]: home = Path.home() patterns: list[str] = [] if sys.platform == "win32": local = Path(os.environ.get("LOCALAPPDATA", home / "AppData" / "Local")) appdata = Path(os.environ.get("APPDATA", home / "AppData" / "Roaming")) patterns += [ str(local / "Google" / "Chrome" / "User Data" / "*" / "Bookmarks"), str(local / "Microsoft" / "Edge" / "User Data" / "*" / "Bookmarks"), str(local / "BraveSoftware" / "Brave-Browser" / "User Data" / "*" / "Bookmarks"), str(appdata / "Mozilla" / "Firefox" / "Profiles" / "*" / "places.sqlite"), ] elif sys.platform == "darwin": support = home / "Library" / "Application Support" patterns += [ str(support / "Google" / "Chrome" / "*" / "Bookmarks"), str(support / "Microsoft Edge" / "*" / "Bookmarks"), str(support / "BraveSoftware" / "Brave-Browser" / "*" / "Bookmarks"), str(home / "Library" / "Safari" / "Bookmarks.plist"), str(support / "Firefox" / "Profiles" / "*" / "places.sqlite"), ] else: config = home / ".config" patterns += [ str(config / "google-chrome" / "*" / "Bookmarks"), str(config / "chromium" / "*" / "Bookmarks"), str(config / "microsoft-edge" / "*" / "Bookmarks"), str(config / "BraveSoftware" / "Brave-Browser" / "*" / "Bookmarks"), str(home / ".mozilla" / "firefox" / "*" / "places.sqlite"), ] return patterns def expand_paths(items: list[str]) -> list[Path]: result: list[Path] = [] for item in items: path = Path(item).expanduser() if path.is_file(): result.append(path) elif path.is_dir(): for name in ("Bookmarks", "places.sqlite", "Bookmarks.plist"): result.extend(candidate for candidate in path.rglob(name) if candidate.is_file()) return sorted(set(path.resolve() for path in result)) def safe_label(value: str) -> str: return re.sub(r"[^A-Za-z0-9._-]+", "_", value) def main() -> int: parser = argparse.ArgumentParser(description="Копия файлов закладок") parser.add_argument("--source", action="append", default=[], help="Файл или папка профиля") parser.add_argument("--dest", type=Path, required=True) parser.add_argument("--apply", action="store_true", help="Выполнить копирование") args = parser.parse_args() if args.source: sources = expand_paths(args.source) else: sources = expand_paths(default_patterns()) if not sources: print("Файлы закладок не найдены. Укажите профиль через --source.", file=sys.stderr) return 1 dest = args.dest.expanduser().resolve() timestamp = time.strftime("%Y%m%d-%H%M%S") target_root = dest / f"bookmarks-{timestamp}" if target_root.exists(): parser.error(f"Каталог уже существует: {target_root}") planned: list[tuple[Path, Path]] = [] for index, source in enumerate(sources, 1): label = f"{index:02d}-{safe_label(source.parent.name)}-{safe_label(source.name)}" planned.append((source, target_root / label)) if source.name == "places.sqlite": for suffix in ("-wal", "-shm"): sidecar = source.with_name(source.name + suffix) if sidecar.is_file(): planned.append((sidecar, target_root / (label + suffix))) for source, target in planned: if args.apply: print(f"Копирование: {source} -> {target.name}") else: print(f"Будет скопировано: {source} -> {target.name}") if not args.apply: print(f"Найдено файлов: {len(planned)}. Для копирования добавьте --apply.") return 0 target_root.mkdir(parents=True, exist_ok=True) entries = [] errors = 0 for source, target in planned: try: shutil.copy2(source, target) entries.append( { "source": str(source), "target": str(target), "size": target.stat().st_size, "sha256": file_digest(target), } ) except OSError as error: errors += 1 print(f"Ошибка {source}: {error}", file=sys.stderr) manifest_path = target_root / "manifest.json" manifest_path.write_text( json.dumps({"files": entries}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"Скопировано: {len(entries)}, ошибок: {errors}") print(f"Manifest: {manifest_path}") return 1 if errors else 0 if __name__ == "__main__": sys.exit(main())