pathflow-toolkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
path_file/sync.py ADDED
@@ -0,0 +1,384 @@
1
+ """Directory synchronization utilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import os
7
+ import shutil
8
+ from pathlib import Path
9
+
10
+ from path_file._internal._iterators import WalkConfig, walk
11
+ from path_file._internal._log import get_logger
12
+ from path_file.entries import SyncDiff, SyncResult
13
+ from path_file.exceptions import SyncConflictError
14
+ from path_file.hash import hash_file
15
+
16
+ logger = get_logger(__name__)
17
+
18
+
19
+ # ──────────────────────────────────────────────────────────────────────────────
20
+ # GITIGNORE-STYLE PATTERN MATCHER
21
+ # ──────────────────────────────────────────────────────────────────────────────
22
+
23
+
24
+ class IgnoreMatcher:
25
+ """Gitignore-style pattern matcher."""
26
+
27
+ def __init__(self, patterns: list[str] | None = None) -> None:
28
+ self.patterns: list[tuple[bool, str]] = [] # (negate, pattern)
29
+ if patterns:
30
+ for p in patterns:
31
+ self.add_pattern(p)
32
+
33
+ def add_pattern(self, pattern: str) -> None:
34
+ """Add a pattern."""
35
+ pattern = pattern.strip()
36
+ if not pattern or pattern.startswith("#"):
37
+ return
38
+
39
+ negate = pattern.startswith("!")
40
+ if negate:
41
+ pattern = pattern[1:]
42
+
43
+ self.patterns.append((negate, pattern))
44
+
45
+ def load_file(self, path: Path) -> None:
46
+ """Load patterns from .gitignore-style file."""
47
+ try:
48
+ content = path.read_text(encoding="utf-8")
49
+ for line in content.splitlines():
50
+ self.add_pattern(line)
51
+ except (OSError, PermissionError):
52
+ pass
53
+
54
+ def match(self, path: Path, is_dir: bool = False) -> bool:
55
+ """
56
+ Check if path matches any pattern.
57
+ Returns True if should be ignored.
58
+ """
59
+ # Get relative path for matching
60
+ path_str = str(path)
61
+
62
+ result = False
63
+ for negate, pattern in self.patterns:
64
+ if self._match_pattern(path_str, pattern, is_dir):
65
+ result = not negate
66
+
67
+ return result
68
+
69
+ def _match_pattern(self, path: str, pattern: str, is_dir: bool) -> bool:
70
+ """Match a single pattern."""
71
+ # Normalize path separators
72
+ path = path.replace("/", os.sep).replace("\\", os.sep)
73
+
74
+ # Normalize pattern
75
+ orig_pattern = pattern
76
+ pattern = pattern.rstrip("/")
77
+
78
+ # Check if this is a directory pattern (ends with /)
79
+ is_dir_pattern = orig_pattern.endswith("/")
80
+
81
+ # If it's a directory pattern but we're matching a file, check if file is inside that dir
82
+ if is_dir_pattern:
83
+ # Pattern like "build" should match "build/" (dir) and "build/file.txt" (file in dir)
84
+ # But NOT "src/build" or "src/build/file.txt"
85
+ if is_dir:
86
+ # Matching a directory - exact match on basename or full path
87
+ return fnmatch.fnmatch(os.path.basename(path), pattern) or fnmatch.fnmatch(
88
+ path, pattern
89
+ )
90
+ else:
91
+ # Matching a file - check if file is directly inside the directory (not nested)
92
+ # path = "build/file.txt", pattern = "build"
93
+ # Should match: path starts with pattern + sep AND pattern is the first component
94
+ return path == pattern or (path.startswith(pattern + os.sep))
95
+
96
+ # Handle **/
97
+ if pattern.startswith("**/"):
98
+ # Match anywhere in path
99
+ rest = pattern[3:]
100
+ return fnmatch.fnmatch(os.path.basename(path), rest) or any(
101
+ fnmatch.fnmatch(part, rest) for part in path.split(os.sep)
102
+ )
103
+
104
+ # Handle /*/ (any directory)
105
+ if "/*/" in pattern:
106
+ # Convert to regex-like
107
+ pass
108
+
109
+ # Simple fnmatch - match against full path or basename
110
+ return fnmatch.fnmatch(os.path.basename(path), pattern) or fnmatch.fnmatch(path, pattern)
111
+
112
+
113
+ # ──────────────────────────────────────────────────────────────────────────────
114
+ # SYNCER
115
+ # ──────────────────────────────────────────────────────────────────────────────
116
+
117
+
118
+ class Syncer:
119
+ """
120
+ Directory synchronization with hash-based comparison.
121
+
122
+ Example:
123
+ syncer = pf.sync("~/Documents", "/backup/Documents")
124
+ syncer.direction("source_to_dest").delete_extras(True).dry_run()
125
+ diff = syncer.compare()
126
+ print(diff.summary())
127
+ syncer.execute()
128
+ """
129
+
130
+ def __init__(
131
+ self,
132
+ source: str | Path,
133
+ dest: str | Path,
134
+ ) -> None:
135
+ self.source = Path(source).resolve()
136
+ self.dest = Path(dest).resolve()
137
+
138
+ self._direction: str = "source_to_dest" # source_to_dest, dest_to_source, bidirectional
139
+ self._ignore_matcher = IgnoreMatcher()
140
+ self._delete_extras = False
141
+ self._dry_run = False
142
+ self._parallel = 1
143
+ self._progress = False
144
+ self._hash_algorithm = "sha256"
145
+ self._workers = 4
146
+
147
+ # Conflict resolution for bidirectional
148
+ self._conflict_strategy: str = "error" # error, source_wins, dest_wins, newer_wins
149
+
150
+ # ─── Configuration ──────────────────────────────────────────────────────
151
+
152
+ def direction(self, d: str) -> Syncer:
153
+ """Set sync direction."""
154
+ if d not in ("source_to_dest", "dest_to_source", "bidirectional"):
155
+ raise ValueError("Direction must be: source_to_dest, dest_to_source, or bidirectional")
156
+ self._direction = d
157
+ return self
158
+
159
+ def ignore(self, patterns: list[str]) -> Syncer:
160
+ """Add ignore patterns."""
161
+ for p in patterns:
162
+ self._ignore_matcher.add_pattern(p)
163
+ return self
164
+
165
+ def ignore_file(self, path: str | Path) -> Syncer:
166
+ """Load ignore patterns from file."""
167
+ self._ignore_matcher.load_file(Path(path))
168
+ return self
169
+
170
+ def delete_extras(self, enabled: bool = True) -> Syncer:
171
+ """Delete files in dest not in source (for source_to_dest)."""
172
+ self._delete_extras = enabled
173
+ return self
174
+
175
+ def dry_run(self, enabled: bool = True) -> Syncer:
176
+ """Enable/disable dry-run mode."""
177
+ self._dry_run = enabled
178
+ return self
179
+
180
+ def parallel(self, workers: int = 4) -> Syncer:
181
+ """Set parallel workers."""
182
+ self._workers = max(1, workers)
183
+ self._parallel = self._workers
184
+ return self
185
+
186
+ def progress(self, enabled: bool = True) -> Syncer:
187
+ """Show progress bar."""
188
+ self._progress = enabled
189
+ return self
190
+
191
+ def hash_algorithm(self, algo: str) -> Syncer:
192
+ """Set hash algorithm for comparison."""
193
+ self._hash_algorithm = algo
194
+ return self
195
+
196
+ def conflict_strategy(self, strategy: str) -> Syncer:
197
+ """Set conflict resolution for bidirectional sync."""
198
+ if strategy not in ("error", "source_wins", "dest_wins", "newer_wins"):
199
+ raise ValueError("Strategy must be: error, source_wins, dest_wins, newer_wins")
200
+ self._conflict_strategy = strategy
201
+ return self
202
+
203
+ # ─── Core Operations ────────────────────────────────────────────────────
204
+
205
+ def compare(self) -> SyncDiff:
206
+ """Compare source and destination, return diff."""
207
+ return self._compute_diff()
208
+
209
+ def execute(self) -> SyncResult:
210
+ """Execute synchronization based on last compare."""
211
+ diff = self._compute_diff()
212
+ return self._apply_diff(diff)
213
+
214
+ def _compute_diff(self) -> SyncDiff:
215
+ """Compute differences between source and dest."""
216
+ diff = SyncDiff()
217
+
218
+ # Walk both directories
219
+ src_files = self._walk_files(self.source)
220
+ dest_files = self._walk_files(self.dest)
221
+
222
+ src_rel = {p.relative_to(self.source): p for p in src_files}
223
+ dest_rel = {p.relative_to(self.dest): p for p in dest_files}
224
+
225
+ all_rel = set(src_rel.keys()) | set(dest_rel.keys())
226
+
227
+ for rel in all_rel:
228
+ src_path = src_rel.get(rel)
229
+ dest_path = dest_rel.get(rel)
230
+
231
+ # Check ignore patterns
232
+ if self._ignore_matcher.match(rel, src_path.is_dir() if src_path else False):
233
+ continue
234
+
235
+ if src_path and not dest_path:
236
+ # New in source
237
+ if self._direction in ("source_to_dest", "bidirectional"):
238
+ diff.to_add.append(rel)
239
+ elif not src_path and dest_path:
240
+ # Only in dest
241
+ if self._direction == "dest_to_source":
242
+ diff.to_add.append(rel) # Add to source
243
+ elif self._direction == "source_to_dest" and self._delete_extras:
244
+ diff.to_delete.append(rel)
245
+ elif src_path and dest_path:
246
+ # In both - compare
247
+ if self._files_differ(src_path, dest_path):
248
+ if self._direction == "bidirectional":
249
+ diff.conflicts.append((src_path, dest_path))
250
+ elif self._direction == "source_to_dest":
251
+ diff.to_update.append(rel)
252
+ elif self._direction == "dest_to_source":
253
+ diff.to_update.append(rel) # Update source
254
+ else:
255
+ diff.unchanged.append(rel)
256
+
257
+ return diff
258
+
259
+ def _files_differ(self, src: Path, dest: Path) -> bool:
260
+ """Check if two files differ using hash."""
261
+ if src.stat().st_size != dest.stat().st_size:
262
+ return True
263
+
264
+ src_hash = hash_file(src, self._hash_algorithm)
265
+ dest_hash = hash_file(dest, self._hash_algorithm)
266
+ return src_hash != dest_hash
267
+
268
+ def _walk_files(self, root: Path) -> list[Path]:
269
+ """Walk directory and return all files."""
270
+ files = []
271
+ config = WalkConfig(follow_symlinks=False)
272
+ for entry in walk(root, config=config):
273
+ if entry.is_file:
274
+ files.append(entry.path)
275
+ return files
276
+
277
+ def _apply_diff(self, diff: SyncDiff) -> SyncResult:
278
+ """Apply the computed diff."""
279
+ errors = []
280
+ count = 0
281
+ total_size = 0
282
+
283
+ if self._dry_run:
284
+ return SyncResult(
285
+ action="sync",
286
+ count=len(diff.to_add) + len(diff.to_update) + len(diff.to_delete),
287
+ total_size=0,
288
+ dry_run=True,
289
+ diff=diff,
290
+ )
291
+
292
+ # Progress bar
293
+ progress_bar = None
294
+ if self._progress:
295
+ from path_file.progress import ProgressBar
296
+
297
+ total = len(diff.to_add) + len(diff.to_update) + len(diff.to_delete)
298
+ progress_bar = ProgressBar(total, prefix="Sync: ")
299
+ progress_bar.__enter__()
300
+
301
+ try:
302
+ # Handle additions/updates
303
+ for rel in diff.to_add + diff.to_update:
304
+ src = self.source / rel
305
+ dest = self.dest / rel
306
+
307
+ try:
308
+ dest.parent.mkdir(parents=True, exist_ok=True)
309
+ shutil.copy2(src, dest)
310
+ count += 1
311
+ total_size += src.stat().st_size
312
+ except Exception as e:
313
+ errors.append((rel, e))
314
+
315
+ if progress_bar:
316
+ progress_bar.update(1)
317
+
318
+ # Handle deletions
319
+ for rel in diff.to_delete:
320
+ dest = self.dest / rel
321
+ try:
322
+ if dest.is_dir():
323
+ shutil.rmtree(dest)
324
+ else:
325
+ dest.unlink()
326
+ count += 1
327
+ except Exception as e:
328
+ errors.append((rel, e))
329
+
330
+ if progress_bar:
331
+ progress_bar.update(1)
332
+
333
+ # Handle conflicts (bidirectional)
334
+ for src, dest in diff.conflicts:
335
+ if self._conflict_strategy == "error":
336
+ src_hash = hash_file(src, self._hash_algorithm)
337
+ dest_hash = hash_file(dest, self._hash_algorithm)
338
+ raise SyncConflictError(
339
+ str(src.relative_to(self.source)),
340
+ src_hash,
341
+ dest_hash,
342
+ )
343
+ elif self._conflict_strategy == "source_wins":
344
+ shutil.copy2(src, dest)
345
+ count += 1
346
+ total_size += src.stat().st_size
347
+ elif self._conflict_strategy == "dest_wins":
348
+ shutil.copy2(dest, src)
349
+ count += 1
350
+ total_size += dest.stat().st_size
351
+ elif self._conflict_strategy == "newer_wins":
352
+ if src.stat().st_mtime > dest.stat().st_mtime:
353
+ shutil.copy2(src, dest)
354
+ else:
355
+ shutil.copy2(dest, src)
356
+ count += 1
357
+
358
+ if progress_bar:
359
+ progress_bar.update(1)
360
+
361
+ finally:
362
+ if progress_bar:
363
+ progress_bar.finish()
364
+ progress_bar.__exit__(None, None, None)
365
+
366
+ return SyncResult(
367
+ action="sync",
368
+ count=count,
369
+ total_size=total_size,
370
+ duration=0.0,
371
+ errors=errors,
372
+ dry_run=self._dry_run,
373
+ diff=diff,
374
+ )
375
+
376
+
377
+ # ──────────────────────────────────────────────────────────────────────────────
378
+ # CONVENIENCE FUNCTION
379
+ # ──────────────────────────────────────────────────────────────────────────────
380
+
381
+
382
+ def sync(source: str | Path, dest: str | Path) -> Syncer:
383
+ """Create a new Syncer."""
384
+ return Syncer(source, dest)