Coverage for src/recycle_bin.py: 100%
70 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"""Recycle bin for obsolete-file cleanup.
3When ``app.recycle_bin.enabled`` is set, files and folders that obsolete-file
4cleanup would delete are moved to ``<app.root>/Recently Deleted/<service>/
5<YYYY-MM-DD>/<path relative to the service destination>`` instead (with the
6library's folder first when Photos libraries have their own destinations), and kept
7for ``app.recycle_bin.retention_days`` (or forever when that is unset).
9The bin only changes *how* cleanup removes something, never *what* it
10removes: with ``remove_obsolete`` off, nothing is cleaned up and nothing
11reaches the bin.
12"""
14import contextlib
15import copy
16import datetime
17import os
18import shutil
19from pathlib import Path
21from src import get_logger
23LOGGER = get_logger()
25BIN_DIRECTORY_NAME = "Recently Deleted"
28class RecycleBin:
29 """Where one service's cleanup puts what it removes."""
31 def __init__(
32 self,
33 root: str,
34 service: str,
35 retention_days: int | None = None,
36 today: datetime.date | None = None,
37 ):
38 """Create the bin for ``service`` under ``root``.
40 Args:
41 root: ``app.root``, the parent of every service destination
42 service: ``drive`` or ``photos``; each gets its own folder
43 retention_days: Days to keep a day's folder; None keeps forever
44 today: Override for tests
45 """
46 self.path = os.path.abspath(os.path.join(root, BIN_DIRECTORY_NAME, service))
47 self.retention_days = retention_days
48 self.today = today or datetime.date.today()
49 self.subfolder = ""
51 def within(self, subfolder: str) -> RecycleBin:
52 """The same bin, filing what it receives under ``subfolder`` in each day.
54 Several destinations can share one service's bin -- each Photos
55 library in ``library_destinations`` has its own -- and the same
56 relative path in two of them must land in two places, or nothing
57 says where either belongs.
58 """
59 scoped = copy.copy(self)
60 scoped.subfolder = subfolder
61 return scoped
63 def contains(self, path: str) -> bool:
64 """True if ``path`` is the bin or inside it.
66 A destination can be ``app.root`` itself, so cleanup walks would
67 otherwise find the bin and treat everything in it as obsolete.
68 """
69 absolute = os.path.abspath(path)
70 top = os.path.dirname(self.path)
71 return absolute == top or absolute.startswith(top + os.sep)
73 def discard(self, path: str, destination_path: str) -> str:
74 """Move ``path`` into today's folder, keeping its place in the tree.
76 Args:
77 path: File or folder that cleanup would delete
78 destination_path: The service destination ``path`` lives under
80 Returns:
81 Where it was moved to
82 """
83 relative = os.path.relpath(
84 os.path.abspath(path), os.path.abspath(destination_path),
85 )
86 day = os.path.join(self.path, self.today.isoformat())
87 target = os.path.normpath(os.path.join(day, self.subfolder, relative))
88 if not target.startswith(day + os.sep):
89 msg = f"Recycle bin: {path} would be filed outside the bin, at {target}"
90 raise ValueError(msg)
91 os.makedirs(os.path.dirname(target), exist_ok=True)
92 # The same path can be removed twice in a day (re-downloaded, then
93 # dropped again); keep both rather than overwrite the first. The
94 # number goes before a file's extension, so renaming it back to the
95 # original name is all a restore takes.
96 stem, extension = (target, "") if os.path.isdir(path) else os.path.splitext(target)
97 candidate, n = target, 2
98 while os.path.lexists(candidate):
99 candidate = f"{stem} ({n}){extension}"
100 n += 1
101 try:
102 shutil.move(path, candidate)
103 except OSError:
104 # Across devices a move is a copy, then a delete. When the delete
105 # fails (the original is locked, or not ours to delete), the copy
106 # would stay behind and the next sync would add another.
107 if os.path.lexists(path) and os.path.lexists(candidate):
108 if os.path.isdir(candidate) and not os.path.islink(candidate):
109 shutil.rmtree(candidate, ignore_errors=True)
110 else:
111 with contextlib.suppress(OSError):
112 os.remove(candidate)
113 raise
114 return candidate
116 def purge(self) -> int:
117 """Delete day folders older than the retention period.
119 Returns:
120 Number of day folders deleted
121 """
122 if self.retention_days is None or not os.path.isdir(self.path):
123 return 0
124 cutoff = self.today - datetime.timedelta(days=self.retention_days)
125 purged = 0
126 for day in sorted(Path(self.path).iterdir()):
127 try:
128 day_date = datetime.date.fromisoformat(day.name)
129 except ValueError:
130 continue # not a folder the bin made; leave it alone
131 if day.is_dir() and day_date < cutoff:
132 LOGGER.info(
133 f"Recycle bin: deleting {day}, older than {self.retention_days} days ...",
134 )
135 try:
136 shutil.rmtree(day)
137 except OSError as e:
138 # Like a stuck file in the cleanup that follows: leave it,
139 # say so, and try again next sync rather than end the pass.
140 LOGGER.warning(f"Recycle bin: could not delete {day}: {e!s}. Trying again next sync.")
141 continue
142 purged += 1
143 return purged
146def from_config(config: dict | None, service: str) -> RecycleBin | None:
147 """The bin for ``service`` if ``app.recycle_bin.enabled``, else None."""
148 from src import config_parser
150 if not config or not config_parser.get_recycle_bin_enabled(config=config):
151 return None
152 return RecycleBin(
153 root=config_parser.get_root_destination_path(config=config),
154 service=service,
155 retention_days=config_parser.get_recycle_bin_retention_days(config=config),
156 )