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/__init__.py +223 -0
- path_file/__main__.py +6 -0
- path_file/_internal/__init__.py +87 -0
- path_file/_internal/_iterators.py +349 -0
- path_file/_internal/_log.py +153 -0
- path_file/_internal/_parsers.py +234 -0
- path_file/_internal/_safety.py +268 -0
- path_file/_version.py +1 -0
- path_file/actions.py +855 -0
- path_file/archive.py +447 -0
- path_file/chain.py +1028 -0
- path_file/cli.py +582 -0
- path_file/entries.py +459 -0
- path_file/exceptions.py +174 -0
- path_file/filters.py +654 -0
- path_file/hash.py +338 -0
- path_file/progress.py +321 -0
- path_file/py.typed +0 -0
- path_file/report.py +348 -0
- path_file/rules.py +481 -0
- path_file/search.py +472 -0
- path_file/sync.py +384 -0
- path_file/units.py +420 -0
- path_file/utils.py +509 -0
- path_file/watch.py +310 -0
- pathflow_toolkit-0.1.0.dist-info/METADATA +219 -0
- pathflow_toolkit-0.1.0.dist-info/RECORD +30 -0
- pathflow_toolkit-0.1.0.dist-info/WHEEL +4 -0
- pathflow_toolkit-0.1.0.dist-info/entry_points.txt +2 -0
- pathflow_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
path_file/entries.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
"""Core data classes for path_file: Entry, ActionResult, Report, SyncDiff, SyncResult."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import hashlib
|
|
7
|
+
import io
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import (
|
|
14
|
+
IO,
|
|
15
|
+
Any,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from path_file.units import human_ago, human_size
|
|
19
|
+
|
|
20
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
21
|
+
# ENTRY
|
|
22
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Entry:
|
|
26
|
+
"""
|
|
27
|
+
Represents a filesystem entry with rich metadata.
|
|
28
|
+
|
|
29
|
+
This is the core data object used throughout path_file. It wraps a path
|
|
30
|
+
and its os.stat_result, providing lazy-loaded properties and helper methods.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
__slots__ = (
|
|
34
|
+
"_content_bytes",
|
|
35
|
+
"_content_text",
|
|
36
|
+
"_hash_sha256",
|
|
37
|
+
"_path",
|
|
38
|
+
"_rule_action",
|
|
39
|
+
"_rule_dest",
|
|
40
|
+
"_rule_params",
|
|
41
|
+
"_stat",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
def __init__(self, path: str | Path, stat_result: os.stat_result | None = None) -> None:
|
|
45
|
+
_p = Path(path)
|
|
46
|
+
# Resolve for a canonical absolute path, but keep symlink identity
|
|
47
|
+
# (resolve() would replace a symlink with its target).
|
|
48
|
+
try:
|
|
49
|
+
self._path = Path(os.path.abspath(_p)) if _p.is_symlink() else _p.resolve()
|
|
50
|
+
except (OSError, ValueError):
|
|
51
|
+
self._path = _p
|
|
52
|
+
self._stat = stat_result or self._path.stat()
|
|
53
|
+
self._hash_sha256: str | None = None
|
|
54
|
+
self._content_text: str | None = None
|
|
55
|
+
self._content_bytes: bytes | None = None
|
|
56
|
+
self._rule_action: str | None = None
|
|
57
|
+
self._rule_dest: str | None = None
|
|
58
|
+
self._rule_params: dict[str, Any] | None = None
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def from_path(cls, path: str | Path) -> Entry:
|
|
62
|
+
"""Create Entry from path, resolving and getting stat."""
|
|
63
|
+
p = Path(os.path.abspath(path)) if Path(path).is_symlink() else Path(path).resolve()
|
|
64
|
+
return cls(p, p.stat())
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def from_stat(cls, path: Path, stat: os.stat_result) -> Entry:
|
|
68
|
+
"""Create Entry from pre-resolved path and stat result (faster)."""
|
|
69
|
+
return cls(path, stat)
|
|
70
|
+
|
|
71
|
+
# ─── Properties ───────────────────────────────────────────────────────────
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def path(self) -> Path:
|
|
75
|
+
"""Resolved absolute path."""
|
|
76
|
+
return self._path
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def name(self) -> str:
|
|
80
|
+
"""File/directory name."""
|
|
81
|
+
return self._path.name
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def stem(self) -> str:
|
|
85
|
+
"""File name without last suffix."""
|
|
86
|
+
return self._path.stem
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def suffix(self) -> str:
|
|
90
|
+
"""Last file suffix (e.g., '.txt')."""
|
|
91
|
+
return self._path.suffix
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def extensions(self) -> list[str]:
|
|
95
|
+
"""All suffixes (e.g., ['.tar', '.gz'] for 'file.tar.gz')."""
|
|
96
|
+
return self._path.suffixes
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def size(self) -> int:
|
|
100
|
+
"""File size in bytes."""
|
|
101
|
+
return self._stat.st_size
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def size_human(self) -> str:
|
|
105
|
+
"""Human-readable file size."""
|
|
106
|
+
return human_size(self.size)
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def created(self) -> datetime:
|
|
110
|
+
"""Creation time (platform-dependent)."""
|
|
111
|
+
return datetime.fromtimestamp(self._stat.st_ctime)
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def modified(self) -> datetime:
|
|
115
|
+
"""Last modification time."""
|
|
116
|
+
return datetime.fromtimestamp(self._stat.st_mtime)
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def accessed(self) -> datetime:
|
|
120
|
+
"""Last access time."""
|
|
121
|
+
return datetime.fromtimestamp(self._stat.st_atime)
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def modified_ago(self) -> str:
|
|
125
|
+
"""Human-readable time since modification."""
|
|
126
|
+
return human_ago(self.modified)
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def created_ago(self) -> str:
|
|
130
|
+
"""Human-readable time since creation."""
|
|
131
|
+
return human_ago(self.created)
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def is_file(self) -> bool:
|
|
135
|
+
"""True if regular file (or a symlink pointing to a regular file)."""
|
|
136
|
+
fmt = self._stat.st_mode & 0o170000
|
|
137
|
+
if fmt == 0o100000:
|
|
138
|
+
return True
|
|
139
|
+
if fmt == 0o120000:
|
|
140
|
+
# Symlink: consider it a file when its target is a regular file
|
|
141
|
+
try:
|
|
142
|
+
target_mode = self._path.stat().st_mode & 0o170000
|
|
143
|
+
except (OSError, ValueError):
|
|
144
|
+
return False
|
|
145
|
+
return target_mode == 0o100000
|
|
146
|
+
return False
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def is_dir(self) -> bool:
|
|
150
|
+
"""True if directory."""
|
|
151
|
+
return self._stat.st_mode & 0o170000 == 0o040000
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def is_symlink(self) -> bool:
|
|
155
|
+
"""True if symbolic link."""
|
|
156
|
+
return self._stat.st_mode & 0o170000 == 0o120000
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def is_hidden(self) -> bool:
|
|
160
|
+
"""True if hidden (starts with dot or has hidden attribute on Windows)."""
|
|
161
|
+
if self.name.startswith("."):
|
|
162
|
+
return True
|
|
163
|
+
try:
|
|
164
|
+
return bool(self._stat.st_file_attributes & 0x2) # Windows FILE_ATTRIBUTE_HIDDEN
|
|
165
|
+
except AttributeError:
|
|
166
|
+
return False
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def is_empty(self) -> bool:
|
|
170
|
+
"""True if file is empty (size 0) or directory has no entries."""
|
|
171
|
+
if self.is_file:
|
|
172
|
+
return self.size == 0
|
|
173
|
+
if self.is_dir:
|
|
174
|
+
try:
|
|
175
|
+
return not any(self._path.iterdir())
|
|
176
|
+
except (PermissionError, OSError):
|
|
177
|
+
return False
|
|
178
|
+
return True
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def hash_sha256(self) -> str:
|
|
182
|
+
"""SHA-256 hash of file content (lazy, cached)."""
|
|
183
|
+
if self._hash_sha256 is None:
|
|
184
|
+
if not self.is_file:
|
|
185
|
+
self._hash_sha256 = ""
|
|
186
|
+
else:
|
|
187
|
+
h = hashlib.sha256()
|
|
188
|
+
with self._path.open("rb") as f:
|
|
189
|
+
for chunk in iter(lambda: f.read(65536), b""):
|
|
190
|
+
h.update(chunk)
|
|
191
|
+
self._hash_sha256 = h.hexdigest()
|
|
192
|
+
return self._hash_sha256
|
|
193
|
+
|
|
194
|
+
# ─── Content Reading ──────────────────────────────────────────────────────
|
|
195
|
+
|
|
196
|
+
def read_text(self, encoding: str = "utf-8") -> str:
|
|
197
|
+
"""Read file as text (lazy, cached)."""
|
|
198
|
+
if self._content_text is None:
|
|
199
|
+
if not self.is_file:
|
|
200
|
+
self._content_text = ""
|
|
201
|
+
else:
|
|
202
|
+
try:
|
|
203
|
+
self._content_text = self._path.read_text(encoding=encoding)
|
|
204
|
+
except UnicodeDecodeError:
|
|
205
|
+
# Fallback to latin-1 which never fails
|
|
206
|
+
self._content_text = self._path.read_text(encoding="latin-1")
|
|
207
|
+
return self._content_text
|
|
208
|
+
|
|
209
|
+
def read_bytes(self) -> bytes:
|
|
210
|
+
"""Read file as bytes (lazy, cached)."""
|
|
211
|
+
if self._content_bytes is None:
|
|
212
|
+
if not self.is_file:
|
|
213
|
+
self._content_bytes = b""
|
|
214
|
+
else:
|
|
215
|
+
self._content_bytes = self._path.read_bytes()
|
|
216
|
+
return self._content_bytes
|
|
217
|
+
|
|
218
|
+
def open(self, mode: str = "r", **kwargs: Any) -> IO[Any]:
|
|
219
|
+
"""Open file with given mode."""
|
|
220
|
+
return self._path.open(mode, **kwargs)
|
|
221
|
+
|
|
222
|
+
# ─── Path Operations ──────────────────────────────────────────────────────
|
|
223
|
+
|
|
224
|
+
def relative_to(self, base: str | Path) -> Path:
|
|
225
|
+
"""Return path relative to base."""
|
|
226
|
+
return self._path.relative_to(Path(base).resolve())
|
|
227
|
+
|
|
228
|
+
def as_dict(self) -> dict[str, Any]:
|
|
229
|
+
"""Convert to dictionary for serialization."""
|
|
230
|
+
return {
|
|
231
|
+
"path": str(self._path),
|
|
232
|
+
"name": self.name,
|
|
233
|
+
"stem": self.stem,
|
|
234
|
+
"suffix": self.suffix,
|
|
235
|
+
"extensions": self.extensions,
|
|
236
|
+
"size": self.size,
|
|
237
|
+
"size_human": self.size_human,
|
|
238
|
+
"created": self.created.isoformat(),
|
|
239
|
+
"modified": self.modified.isoformat(),
|
|
240
|
+
"accessed": self.accessed.isoformat(),
|
|
241
|
+
"is_file": self.is_file,
|
|
242
|
+
"is_dir": self.is_dir,
|
|
243
|
+
"is_symlink": self.is_symlink,
|
|
244
|
+
"is_hidden": self.is_hidden,
|
|
245
|
+
"is_empty": self.is_empty,
|
|
246
|
+
"hash_sha256": self.hash_sha256 if self.is_file else None,
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
# ─── Dunder Methods ───────────────────────────────────────────────────────
|
|
250
|
+
|
|
251
|
+
def __str__(self) -> str:
|
|
252
|
+
return str(self._path)
|
|
253
|
+
|
|
254
|
+
def __repr__(self) -> str:
|
|
255
|
+
type_char = "f" if self.is_file else "d" if self.is_dir else "l"
|
|
256
|
+
return f"<Entry {type_char} {self._path} ({self.size_human})>"
|
|
257
|
+
|
|
258
|
+
def __eq__(self, other: object) -> bool:
|
|
259
|
+
if not isinstance(other, Entry):
|
|
260
|
+
return NotImplemented
|
|
261
|
+
return self._path == other._path
|
|
262
|
+
|
|
263
|
+
def __hash__(self) -> int:
|
|
264
|
+
return hash(self._path)
|
|
265
|
+
|
|
266
|
+
def __lt__(self, other: Entry) -> bool:
|
|
267
|
+
if not isinstance(other, Entry):
|
|
268
|
+
return NotImplemented
|
|
269
|
+
return str(self._path) < str(other._path)
|
|
270
|
+
|
|
271
|
+
def __fspath__(self) -> str:
|
|
272
|
+
return str(self._path)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
276
|
+
# ACTION RESULT
|
|
277
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@dataclass
|
|
281
|
+
class ActionResult:
|
|
282
|
+
"""Result of an action execution (copy, move, delete, etc.)."""
|
|
283
|
+
|
|
284
|
+
action: str
|
|
285
|
+
count: int = 0
|
|
286
|
+
total_size: int = 0
|
|
287
|
+
duration: float = 0.0
|
|
288
|
+
errors: list[tuple[Path, Exception]] = field(default_factory=list)
|
|
289
|
+
skipped: int = 0
|
|
290
|
+
dry_run: bool = False
|
|
291
|
+
|
|
292
|
+
def success(self) -> bool:
|
|
293
|
+
"""True if no errors occurred."""
|
|
294
|
+
return len(self.errors) == 0
|
|
295
|
+
|
|
296
|
+
def summary(self) -> str:
|
|
297
|
+
"""Human-readable summary."""
|
|
298
|
+
status = "DRY RUN" if self.dry_run else "COMPLETED"
|
|
299
|
+
error_info = f", {len(self.errors)} errors" if self.errors else ""
|
|
300
|
+
skip_info = f", {self.skipped} skipped" if self.skipped else ""
|
|
301
|
+
return (
|
|
302
|
+
f"{self.action.upper()} {status}: {self.count} file(s), "
|
|
303
|
+
f"{human_size(self.total_size)} in {self.duration:.2f}s"
|
|
304
|
+
f"{error_info}{skip_info}"
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
def to_dict(self) -> dict[str, Any]:
|
|
308
|
+
"""Convert to dictionary."""
|
|
309
|
+
return {
|
|
310
|
+
"action": self.action,
|
|
311
|
+
"count": self.count,
|
|
312
|
+
"total_size": self.total_size,
|
|
313
|
+
"total_size_human": human_size(self.total_size),
|
|
314
|
+
"duration": self.duration,
|
|
315
|
+
"errors": [{"path": str(p), "error": str(e)} for p, e in self.errors],
|
|
316
|
+
"skipped": self.skipped,
|
|
317
|
+
"dry_run": self.dry_run,
|
|
318
|
+
"success": self.success(),
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
323
|
+
# REPORT
|
|
324
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
@dataclass
|
|
328
|
+
class Report:
|
|
329
|
+
"""Aggregated report of a file collection."""
|
|
330
|
+
|
|
331
|
+
chain_size: int = 0
|
|
332
|
+
total_size: int = 0
|
|
333
|
+
by_extension: dict[str, int] = field(default_factory=dict)
|
|
334
|
+
by_size_bucket: dict[str, int] = field(default_factory=dict)
|
|
335
|
+
largest: Entry | None = None
|
|
336
|
+
smallest: Entry | None = None
|
|
337
|
+
oldest: Entry | None = None
|
|
338
|
+
newest: Entry | None = None
|
|
339
|
+
file_count: int = 0
|
|
340
|
+
dir_count: int = 0
|
|
341
|
+
symlink_count: int = 0
|
|
342
|
+
hidden_count: int = 0
|
|
343
|
+
empty_count: int = 0
|
|
344
|
+
|
|
345
|
+
def to_dict(self) -> dict[str, Any]:
|
|
346
|
+
"""Convert to dictionary."""
|
|
347
|
+
return {
|
|
348
|
+
"chain_size": self.chain_size,
|
|
349
|
+
"total_size": self.total_size,
|
|
350
|
+
"total_size_human": human_size(self.total_size),
|
|
351
|
+
"by_extension": self.by_extension,
|
|
352
|
+
"by_size_bucket": self.by_size_bucket,
|
|
353
|
+
"largest": self.largest.as_dict() if self.largest else None,
|
|
354
|
+
"smallest": self.smallest.as_dict() if self.smallest else None,
|
|
355
|
+
"oldest": self.oldest.as_dict() if self.oldest else None,
|
|
356
|
+
"newest": self.newest.as_dict() if self.newest else None,
|
|
357
|
+
"file_count": self.file_count,
|
|
358
|
+
"dir_count": self.dir_count,
|
|
359
|
+
"symlink_count": self.symlink_count,
|
|
360
|
+
"hidden_count": self.hidden_count,
|
|
361
|
+
"empty_count": self.empty_count,
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
def to_json(self, indent: int = 2) -> str:
|
|
365
|
+
"""Convert to JSON string."""
|
|
366
|
+
return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
|
|
367
|
+
|
|
368
|
+
def to_csv(self) -> str:
|
|
369
|
+
"""Convert to CSV string (extension breakdown)."""
|
|
370
|
+
output = io.StringIO()
|
|
371
|
+
writer = csv.writer(output)
|
|
372
|
+
writer.writerow(["Extension", "Count", "Size", "Size Human"])
|
|
373
|
+
for ext, count in sorted(self.by_extension.items(), key=lambda x: -x[1]):
|
|
374
|
+
writer.writerow([ext, count, "", human_size(count)]) # size per ext not tracked
|
|
375
|
+
return output.getvalue()
|
|
376
|
+
|
|
377
|
+
def to_table(self) -> str:
|
|
378
|
+
"""Pretty ASCII table."""
|
|
379
|
+
lines = []
|
|
380
|
+
lines.append("┌────────────────────────────────────────────────────────────┐")
|
|
381
|
+
lines.append("│ PATHFLOW REPORT │")
|
|
382
|
+
lines.append("├────────────────────────────────────────────────────────────┤")
|
|
383
|
+
lines.append(
|
|
384
|
+
f"│ Files: {self.file_count:<5} Dirs: {self.dir_count:<5} "
|
|
385
|
+
f"Symlinks: {self.symlink_count:<5} Hidden: {self.hidden_count:<5} "
|
|
386
|
+
f"Empty: {self.empty_count:<5} │"
|
|
387
|
+
)
|
|
388
|
+
lines.append(
|
|
389
|
+
f"│ Total Entries: {self.chain_size:<5} Total Size: "
|
|
390
|
+
f"{human_size(self.total_size):>10} │"
|
|
391
|
+
)
|
|
392
|
+
lines.append("├──────────────────┬──────────┬──────────────────────────────┤")
|
|
393
|
+
lines.append("│ Extension │ Count │ Size │")
|
|
394
|
+
lines.append("├──────────────────┼──────────┼──────────────────────────────┤")
|
|
395
|
+
|
|
396
|
+
for ext, count in sorted(self.by_extension.items(), key=lambda x: -x[1]):
|
|
397
|
+
ext_display = ext if ext else "(no extension)"
|
|
398
|
+
lines.append(f"│ {ext_display:<16} │ {count:>8} │ {human_size(count):>28} │")
|
|
399
|
+
|
|
400
|
+
lines.append("└──────────────────┴──────────┴──────────────────────────────┘")
|
|
401
|
+
|
|
402
|
+
if self.largest:
|
|
403
|
+
lines.append(f"\nLargest: {self.largest} ({self.largest.size_human})")
|
|
404
|
+
if self.smallest and self.smallest.size > 0:
|
|
405
|
+
lines.append(f"Smallest: {self.smallest} ({self.smallest.size_human})")
|
|
406
|
+
if self.newest:
|
|
407
|
+
lines.append(f"Newest: {self.newest} (modified {self.newest.modified_ago})")
|
|
408
|
+
if self.oldest:
|
|
409
|
+
lines.append(f"Oldest: {self.oldest} (modified {self.oldest.modified_ago})")
|
|
410
|
+
|
|
411
|
+
return "\n".join(lines)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
415
|
+
# SYNC DIFF & RESULT
|
|
416
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
@dataclass
|
|
420
|
+
class SyncDiff:
|
|
421
|
+
"""Difference between source and destination for sync operations."""
|
|
422
|
+
|
|
423
|
+
to_add: list[Path] = field(default_factory=list)
|
|
424
|
+
to_update: list[Path] = field(default_factory=list)
|
|
425
|
+
to_delete: list[Path] = field(default_factory=list)
|
|
426
|
+
conflicts: list[tuple[Path, Path]] = field(default_factory=list)
|
|
427
|
+
unchanged: list[Path] = field(default_factory=list)
|
|
428
|
+
|
|
429
|
+
def summary(self) -> str:
|
|
430
|
+
"""Human-readable summary."""
|
|
431
|
+
parts = []
|
|
432
|
+
if self.to_add:
|
|
433
|
+
parts.append(f"+{len(self.to_add)} new")
|
|
434
|
+
if self.to_update:
|
|
435
|
+
parts.append(f"~{len(self.to_update)} modified")
|
|
436
|
+
if self.to_delete:
|
|
437
|
+
parts.append(f"-{len(self.to_delete)} to delete")
|
|
438
|
+
if self.conflicts:
|
|
439
|
+
parts.append(f"!{len(self.conflicts)} conflicts")
|
|
440
|
+
if not parts:
|
|
441
|
+
return "Already in sync"
|
|
442
|
+
return ", ".join(parts)
|
|
443
|
+
|
|
444
|
+
def has_changes(self) -> bool:
|
|
445
|
+
"""True if any changes needed."""
|
|
446
|
+
return bool(self.to_add or self.to_update or self.to_delete or self.conflicts)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
@dataclass
|
|
450
|
+
class SyncResult(ActionResult):
|
|
451
|
+
"""Result of a sync operation."""
|
|
452
|
+
|
|
453
|
+
diff: SyncDiff | None = None
|
|
454
|
+
|
|
455
|
+
def summary(self) -> str:
|
|
456
|
+
base = super().summary()
|
|
457
|
+
if self.diff:
|
|
458
|
+
return f"{base} | {self.diff.summary()}"
|
|
459
|
+
return base
|
path_file/exceptions.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Custom exceptions for path_file with helpful hints."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PathflowError(Exception):
|
|
7
|
+
"""Base exception for all path_file errors."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, message: str, hint: str | None = None) -> None:
|
|
10
|
+
self.message = message
|
|
11
|
+
self.hint = hint
|
|
12
|
+
super().__init__(message)
|
|
13
|
+
|
|
14
|
+
def __str__(self) -> str:
|
|
15
|
+
if self.hint:
|
|
16
|
+
return f"{self.message}\nHint: {self.hint}"
|
|
17
|
+
return self.message
|
|
18
|
+
|
|
19
|
+
def __repr__(self) -> str:
|
|
20
|
+
return f"{self.__class__.__name__}({self.message!r}, hint={self.hint!r})"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class FileNotFoundError(PathflowError):
|
|
24
|
+
"""Raised when a file or directory is not found."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, path: str | None = None, hint: str | None = None) -> None:
|
|
27
|
+
msg = f"File not found: {path}" if path else "File not found"
|
|
28
|
+
default_hint = hint if hint else "Check the path exists and you have read permissions"
|
|
29
|
+
super().__init__(msg, default_hint)
|
|
30
|
+
self.path = path
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class PermissionError(PathflowError):
|
|
34
|
+
"""Raised when permission is denied for an operation."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self, path: str | None = None, operation: str | None = None, hint: str | None = None
|
|
38
|
+
) -> None:
|
|
39
|
+
op = f" during {operation}" if operation else ""
|
|
40
|
+
msg = f"Permission denied{op}: {path}" if path else f"Permission denied{op}"
|
|
41
|
+
default_hint = (
|
|
42
|
+
hint if hint else "Run with elevated privileges or check file/folder permissions"
|
|
43
|
+
)
|
|
44
|
+
super().__init__(msg, default_hint)
|
|
45
|
+
self.path = path
|
|
46
|
+
self.operation = operation
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class DestExistsError(PathflowError):
|
|
50
|
+
"""Raised when destination already exists and overwrite is False."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, dest: str | None = None, hint: str | None = None) -> None:
|
|
53
|
+
msg = f"Destination already exists: {dest}" if dest else "Destination already exists"
|
|
54
|
+
default_hint = (
|
|
55
|
+
hint if hint else "Use overwrite=True or remove the existing destination first"
|
|
56
|
+
)
|
|
57
|
+
super().__init__(msg, default_hint)
|
|
58
|
+
self.dest = dest
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class InvalidPatternError(PathflowError):
|
|
62
|
+
"""Raised when a pattern (glob/regex) is invalid."""
|
|
63
|
+
|
|
64
|
+
def __init__(self, pattern: str | None = None, hint: str | None = None) -> None:
|
|
65
|
+
msg = f"Invalid pattern: {pattern}" if pattern else "Invalid pattern"
|
|
66
|
+
default_hint = (
|
|
67
|
+
hint if hint else "Check pattern syntax: use glob patterns (*.txt) or valid regex"
|
|
68
|
+
)
|
|
69
|
+
super().__init__(msg, default_hint)
|
|
70
|
+
self.pattern = pattern
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class InvalidSizeError(PathflowError):
|
|
74
|
+
"""Raised when a size specification is invalid."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, size_spec: str | None = None, hint: str | None = None) -> None:
|
|
77
|
+
msg = f"Invalid size specification: {size_spec}" if size_spec else "Invalid size"
|
|
78
|
+
default_hint = (
|
|
79
|
+
hint if hint else "Use format like '100B', '1KB', '2.5MB', '1GB' (KB, MB, GB supported)"
|
|
80
|
+
)
|
|
81
|
+
super().__init__(msg, default_hint)
|
|
82
|
+
self.size_spec = size_spec
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class InvalidDurationError(PathflowError):
|
|
86
|
+
"""Raised when a duration specification is invalid."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, duration_spec: str | None = None, hint: str | None = None) -> None:
|
|
89
|
+
msg = f"Invalid duration: {duration_spec}" if duration_spec else "Invalid duration"
|
|
90
|
+
default_hint = (
|
|
91
|
+
hint if hint else "Use format like '7 days', '1h', '30m', '1 week', '2 months'"
|
|
92
|
+
)
|
|
93
|
+
super().__init__(msg, default_hint)
|
|
94
|
+
self.duration_spec = duration_spec
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class RulesParseError(PathflowError):
|
|
98
|
+
"""Raised when parsing rules file fails."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, message: str, line: int | None = None, hint: str | None = None) -> None:
|
|
101
|
+
line_info = f" at line {line}" if line else ""
|
|
102
|
+
msg = f"Failed to parse rules{line_info}: {message}"
|
|
103
|
+
default_hint = (
|
|
104
|
+
hint
|
|
105
|
+
if hint
|
|
106
|
+
else "Check TOML syntax: ensure [[rule]] sections have valid keys and values"
|
|
107
|
+
)
|
|
108
|
+
super().__init__(msg, default_hint)
|
|
109
|
+
self.line = line
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class DryRunRequiredError(PathflowError):
|
|
113
|
+
"""Raised when a destructive operation requires explicit confirmation."""
|
|
114
|
+
|
|
115
|
+
def __init__(self, action: str, count: int, hint: str | None = None) -> None:
|
|
116
|
+
msg = f"Destructive operation '{action}' would affect {count} file(s)"
|
|
117
|
+
default_hint = hint if hint else "Use confirm=True to proceed, or dry_run=True to preview"
|
|
118
|
+
super().__init__(msg, default_hint)
|
|
119
|
+
self.action = action
|
|
120
|
+
self.count = count
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class SyncConflictError(PathflowError):
|
|
124
|
+
"""Raised when sync detects a conflict."""
|
|
125
|
+
|
|
126
|
+
def __init__(
|
|
127
|
+
self,
|
|
128
|
+
path: str,
|
|
129
|
+
source_hash: str,
|
|
130
|
+
dest_hash: str,
|
|
131
|
+
hint: str | None = None,
|
|
132
|
+
) -> None:
|
|
133
|
+
msg = f"Sync conflict at {path}: source and destination differ"
|
|
134
|
+
default_hint = (
|
|
135
|
+
hint if hint else "Resolve manually or use direction='source_to_dest' to force"
|
|
136
|
+
)
|
|
137
|
+
super().__init__(msg, default_hint)
|
|
138
|
+
self.path = path
|
|
139
|
+
self.source_hash = source_hash
|
|
140
|
+
self.dest_hash = dest_hash
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class WatchError(PathflowError):
|
|
144
|
+
"""Raised when folder watching encounters an error."""
|
|
145
|
+
|
|
146
|
+
def __init__(self, path: str | None = None, hint: str | None = None) -> None:
|
|
147
|
+
msg = f"Watch error: {path}" if path else "Watch error"
|
|
148
|
+
default_hint = (
|
|
149
|
+
hint if hint else "Check path exists and is readable; watcher uses polling fallback"
|
|
150
|
+
)
|
|
151
|
+
super().__init__(msg, default_hint)
|
|
152
|
+
self.path = path
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class ArchiveError(PathflowError):
|
|
156
|
+
"""Raised when archive operations fail."""
|
|
157
|
+
|
|
158
|
+
def __init__(self, message: str, path: str | None = None, hint: str | None = None) -> None:
|
|
159
|
+
msg = f"Archive error: {message}" + (f" ({path})" if path else "")
|
|
160
|
+
default_hint = (
|
|
161
|
+
hint if hint else "Check archive format is supported and file is not corrupted"
|
|
162
|
+
)
|
|
163
|
+
super().__init__(msg, default_hint)
|
|
164
|
+
self.path = path
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class HashError(PathflowError):
|
|
168
|
+
"""Raised when hash computation fails."""
|
|
169
|
+
|
|
170
|
+
def __init__(self, path: str | None = None, hint: str | None = None) -> None:
|
|
171
|
+
msg = f"Hash computation failed: {path}" if path else "Hash computation failed"
|
|
172
|
+
default_hint = hint if hint else "Check file is readable and not locked by another process"
|
|
173
|
+
super().__init__(msg, default_hint)
|
|
174
|
+
self.path = path
|