Coverage for src/drive_cleanup.py: 100%
40 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
1"""Drive cleanup utilities.
3This module provides cleanup functionality for removing obsolete files
4and directories during iCloud Drive sync operations per SRP.
5"""
7__author__ = "Mandar Patil (mandarons@pm.me)"
9import os
10from pathlib import Path
11from shutil import rmtree
13from src import configure_icloudpy_logging, get_logger
15# Configure icloudpy logging immediately after import
16configure_icloudpy_logging()
18LOGGER = get_logger()
21def remove_obsolete(
22 destination_path: str,
23 files: set[str],
24 recycle_bin=None,
25 exclude_filenames: set[str] | None = None,
26) -> set[str]:
27 """Remove local files and directories that no longer exist remotely.
29 Args:
30 destination_path: Root directory to clean up
31 files: Set of file paths that should be kept (exist remotely)
32 recycle_bin: ``RecycleBin`` to move them to instead of deleting
33 exclude_filenames: Root-level sentinel names to preserve during cleanup
35 Returns:
36 Set of paths that were removed
37 """
38 removed_paths = set()
39 if not (destination_path and files is not None):
40 return removed_paths
41 if recycle_bin:
42 recycle_bin.purge()
44 stuck: list[str] = []
45 for path in Path(destination_path).rglob("*"):
46 local_file = str(path.absolute())
47 if any(local_file.startswith(folder + os.sep) for folder in stuck):
48 continue # inside a folder that could not be removed: already reported
49 if exclude_filenames and path.parent == Path(destination_path) and path.name in exclude_filenames:
50 continue
51 if recycle_bin and recycle_bin.contains(local_file):
52 continue
53 if local_file not in files:
54 if not (path.is_file() or path.is_dir()):
55 continue # already went with a folder removed above
56 try:
57 if recycle_bin:
58 LOGGER.info(f"Moving {local_file} to the recycle bin ...")
59 recycle_bin.discard(local_file, destination_path)
60 else:
61 LOGGER.info(f"Removing {local_file} ...")
62 if path.is_file():
63 path.unlink(missing_ok=True)
64 else:
65 rmtree(local_file)
66 except OSError as e:
67 # Locked by another program, or not this container's to
68 # delete. One such item must not end the pass; it is tried
69 # again next sync.
70 LOGGER.warning(f"Could not remove {local_file}, leaving it: {e!s}")
71 if path.is_dir():
72 stuck.append(local_file)
73 continue
74 removed_paths.add(local_file)
75 return removed_paths