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/chain.py ADDED
@@ -0,0 +1,1028 @@
1
+ """FileChain - immutable, lazy, chainable file collection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+ import json
8
+ from collections.abc import Callable, Iterator, Sequence
9
+ from datetime import datetime, timedelta
10
+ from pathlib import Path
11
+ from typing import (
12
+ TYPE_CHECKING,
13
+ Any,
14
+ )
15
+
16
+ from path_file._internal._iterators import WalkConfig, walk
17
+ from path_file._internal._log import get_logger, log_debug
18
+ from path_file.entries import ActionResult, Entry, Report
19
+ from path_file.exceptions import PathflowError
20
+ from path_file.filters import FilterFunc
21
+
22
+ if TYPE_CHECKING:
23
+ pass
24
+
25
+ logger = get_logger(__name__)
26
+
27
+
28
+ def _as_duration(duration: str | int) -> str | timedelta:
29
+ """Normalize int durations (seconds) to timedelta (matches parse_duration)."""
30
+ return timedelta(seconds=duration) if isinstance(duration, int) else duration
31
+
32
+
33
+ def _apply_context_filters(entries: list[Entry], filters: list[Any]) -> list[Entry]:
34
+ """Apply context-aware (duplicate/unique) filters over ALL entries."""
35
+ markers = dict.fromkeys(getattr(f, "mode", None) for f in filters)
36
+ for marker in markers:
37
+ if marker in ("duplicates_by_hash", "unique_by_hash"):
38
+ entries = _filter_by_hash_groups(
39
+ entries, keep_duplicates=marker == "duplicates_by_hash"
40
+ )
41
+ elif marker in ("duplicates_by_name", "unique_by_name"):
42
+ entries = _filter_by_name_groups(
43
+ entries, keep_duplicates=marker == "duplicates_by_name"
44
+ )
45
+ return entries
46
+
47
+
48
+ def _filter_by_name_groups(entries: list[Entry], *, keep_duplicates: bool) -> list[Entry]:
49
+ """Keep entries whose name appears more than once (or exactly once)."""
50
+ counts: dict[str, int] = {}
51
+ for entry in entries:
52
+ counts[entry.name] = counts.get(entry.name, 0) + 1
53
+ if keep_duplicates:
54
+ return [e for e in entries if counts[e.name] > 1]
55
+ return [e for e in entries if counts[e.name] == 1]
56
+
57
+
58
+ def _filter_by_hash_groups(entries: list[Entry], *, keep_duplicates: bool) -> list[Entry]:
59
+ """Keep files whose content hash appears more than once (or exactly once)."""
60
+ files = [e for e in entries if e.is_file]
61
+ hashes: dict[int, str] = {}
62
+ for entry in files:
63
+ try:
64
+ hashes[id(entry)] = entry.hash_sha256
65
+ except OSError as exc:
66
+ log_debug(f"hash failed for {entry.path}: {exc}")
67
+ counts: dict[str, int] = {}
68
+ for digest in hashes.values():
69
+ counts[digest] = counts.get(digest, 0) + 1
70
+ result = []
71
+ for entry in files:
72
+ entry_digest = hashes.get(id(entry))
73
+ if entry_digest is None:
74
+ continue
75
+ group = counts[entry_digest]
76
+ if (group > 1) if keep_duplicates else (group == 1):
77
+ result.append(entry)
78
+ return result
79
+
80
+
81
+ def _dedupe_entries(entries: list[Entry]) -> list[Entry]:
82
+ """Keep the first occurrence of each resolved path (stateless, repeatable)."""
83
+ seen: set[str] = set()
84
+ unique: list[Entry] = []
85
+ for entry in entries:
86
+ try:
87
+ key = str(entry.path.resolve())
88
+ except OSError:
89
+ key = str(entry.path)
90
+ if key not in seen:
91
+ seen.add(key)
92
+ unique.append(entry)
93
+ return unique
94
+
95
+
96
+ # ──────────────────────────────────────────────────────────────────────────────
97
+ # FILE CHAIN
98
+ # ──────────────────────────────────────────────────────────────────────────────
99
+
100
+
101
+ class _DedupFilter:
102
+ """Marker filter: the real dedup happens in FileChain._materialize()."""
103
+
104
+ _needs_dedup: bool = True
105
+
106
+ def __call__(self, entry: Entry) -> bool:
107
+ return True
108
+
109
+
110
+ class FileChain:
111
+ """
112
+ Immutable, lazy, chainable file collection.
113
+
114
+ All filter methods return NEW FileChain instances.
115
+ All action methods trigger materialization + execution.
116
+
117
+ Example:
118
+ pf.find("~/Downloads")
119
+ .files()
120
+ .with_extension(".jpg")
121
+ .larger_than("2MB")
122
+ .copy_to("~/Pictures/Large")
123
+ """
124
+
125
+ __slots__ = (
126
+ "_action_name",
127
+ "_action_params",
128
+ "_dry_run",
129
+ "_filters",
130
+ "_follow_symlinks",
131
+ "_limit",
132
+ "_max_depth",
133
+ "_min_depth",
134
+ "_on_error",
135
+ "_parallel",
136
+ "_progress",
137
+ "_recursive",
138
+ "_skip",
139
+ "_sort_desc",
140
+ "_sort_key",
141
+ "_source",
142
+ "_verbose",
143
+ )
144
+
145
+ if TYPE_CHECKING:
146
+ # Signatures of the action methods attached dynamically by
147
+ # ``_add_action_methods()`` (declared here for type checkers).
148
+ def copy_to(self, *args: Any, **kwargs: Any) -> FileChain: ...
149
+ def move_to(self, *args: Any, **kwargs: Any) -> FileChain: ...
150
+ def delete(self, *args: Any, **kwargs: Any) -> FileChain: ...
151
+ def trash(self, *args: Any, **kwargs: Any) -> FileChain: ...
152
+ def rename(self, *args: Any, **kwargs: Any) -> FileChain: ...
153
+ def rename_with(self, *args: Any, **kwargs: Any) -> FileChain: ...
154
+ def archive_to(self, *args: Any, **kwargs: Any) -> FileChain: ...
155
+ def compress(self, *args: Any, **kwargs: Any) -> FileChain: ...
156
+ def extract_to(self, *args: Any, **kwargs: Any) -> FileChain: ...
157
+ def chmod(self, *args: Any, **kwargs: Any) -> FileChain: ...
158
+ def touch(self, *args: Any, **kwargs: Any) -> FileChain: ...
159
+ def read_text(self, *args: Any, **kwargs: Any) -> FileChain: ...
160
+ def read_bytes(self, *args: Any, **kwargs: Any) -> FileChain: ...
161
+ def write_text(self, *args: Any, **kwargs: Any) -> FileChain: ...
162
+ def write_bytes(self, *args: Any, **kwargs: Any) -> FileChain: ...
163
+ def hash(self, *args: Any, **kwargs: Any) -> FileChain: ...
164
+ def open(self, *args: Any, **kwargs: Any) -> FileChain: ...
165
+ def create_dir(self, *args: Any, **kwargs: Any) -> FileChain: ...
166
+ def symlink_to(self, *args: Any, **kwargs: Any) -> FileChain: ...
167
+
168
+ def __init__(
169
+ self,
170
+ source: str | Path | Sequence[str | Path] | Sequence[Entry] | Iterator[Entry],
171
+ filters: list[FilterFunc] | None = None,
172
+ sort_key: str | None = None,
173
+ sort_desc: bool = False,
174
+ limit: int | None = None,
175
+ skip: int = 0,
176
+ parallel: int = 1,
177
+ progress: bool = False,
178
+ dry_run: bool | None = None,
179
+ on_error: str = "raise",
180
+ verbose: bool = False,
181
+ recursive: bool = True,
182
+ follow_symlinks: bool = False,
183
+ max_depth: int | None = None,
184
+ min_depth: int = 0,
185
+ action_name: str | None = None,
186
+ action_params: dict[str, Any] | None = None,
187
+ ) -> None:
188
+ self._source = source
189
+ self._filters = filters or []
190
+ self._sort_key = sort_key
191
+ self._sort_desc = sort_desc
192
+ self._limit = limit
193
+ self._skip = skip
194
+ self._parallel = max(1, parallel)
195
+ self._progress = progress
196
+ self._dry_run = dry_run
197
+ self._on_error = on_error # "raise", "skip", "collect"
198
+ self._verbose = verbose
199
+ self._recursive = recursive
200
+ self._follow_symlinks = follow_symlinks
201
+ self._max_depth = max_depth
202
+ self._min_depth = min_depth
203
+ self._action_name = action_name
204
+ self._action_params = action_params or {}
205
+
206
+ # ─── Factory Methods ──────────────────────────────────────────────────────
207
+
208
+ @classmethod
209
+ def from_paths(cls, paths: Sequence[str | Path]) -> FileChain:
210
+ """Create chain from explicit list of paths."""
211
+ entries = [Entry.from_path(p) for p in paths]
212
+ return cls(entries, filters=[])
213
+
214
+ @classmethod
215
+ def from_entries(cls, entries: Sequence[Entry]) -> FileChain:
216
+ """Create chain from Entry objects."""
217
+ return cls(list(entries), filters=[])
218
+
219
+ # ─── Internal Helpers ─────────────────────────────────────────────────────
220
+
221
+ def _with_filter(self, filter_func: FilterFunc) -> FileChain:
222
+ """Return new chain with additional filter."""
223
+ return FileChain(
224
+ self._source,
225
+ filters=[*self._filters, filter_func],
226
+ sort_key=self._sort_key,
227
+ sort_desc=self._sort_desc,
228
+ limit=self._limit,
229
+ skip=self._skip,
230
+ parallel=self._parallel,
231
+ progress=self._progress,
232
+ dry_run=self._dry_run,
233
+ on_error=self._on_error,
234
+ verbose=self._verbose,
235
+ recursive=self._recursive,
236
+ follow_symlinks=self._follow_symlinks,
237
+ max_depth=self._max_depth,
238
+ min_depth=self._min_depth,
239
+ action_name=self._action_name,
240
+ action_params=self._action_params,
241
+ )
242
+
243
+ def _with_config(self, **kwargs: Any) -> FileChain:
244
+ """Return new chain with modified configuration."""
245
+ return FileChain(
246
+ self._source,
247
+ filters=self._filters,
248
+ sort_key=kwargs.get("sort_key", self._sort_key),
249
+ sort_desc=kwargs.get("sort_desc", self._sort_desc),
250
+ limit=kwargs.get("limit", self._limit),
251
+ skip=kwargs.get("skip", self._skip),
252
+ parallel=kwargs.get("parallel", self._parallel),
253
+ progress=kwargs.get("progress", self._progress),
254
+ dry_run=self._dry_run if kwargs.get("dry_run") is None else kwargs.get("dry_run"),
255
+ on_error=kwargs.get("on_error", self._on_error),
256
+ verbose=kwargs.get("verbose", self._verbose),
257
+ recursive=kwargs.get("recursive", self._recursive),
258
+ follow_symlinks=kwargs.get("follow_symlinks", self._follow_symlinks),
259
+ max_depth=kwargs.get("max_depth", self._max_depth),
260
+ min_depth=kwargs.get("min_depth", self._min_depth),
261
+ action_name=kwargs.get("action_name", self._action_name),
262
+ action_params=kwargs.get("action_params", self._action_params),
263
+ )
264
+
265
+ def _iter(self) -> Iterator[Entry]:
266
+ """Internal: yields filtered entries (lazy)."""
267
+ yield from self._materialize_iter()
268
+
269
+ def _materialize_iter(self) -> Iterator[Entry]:
270
+ """Internal: iterate over filtered entries without collecting all."""
271
+ # Get raw entries
272
+ if isinstance(self._source, (str, Path)):
273
+ # Walk directory
274
+ config = WalkConfig(
275
+ follow_symlinks=self._follow_symlinks,
276
+ # recursive=False means root level only (depth 0)
277
+ max_depth=self._max_depth if self._recursive else 0,
278
+ min_depth=self._min_depth,
279
+ )
280
+ raw_entries: Iterator[Entry] | list[Entry] = walk(self._source, config=config)
281
+ elif isinstance(self._source, Iterator):
282
+ raw_entries = self._source
283
+ else:
284
+ # Assume sequence of paths or entries
285
+ collected: list[Entry] = []
286
+ for item in self._source:
287
+ if isinstance(item, Entry):
288
+ collected.append(item)
289
+ else:
290
+ collected.append(Entry.from_path(item))
291
+ raw_entries = collected
292
+
293
+ # Apply filters
294
+ for entry in raw_entries:
295
+ try:
296
+ if all(f(entry) for f in self._filters):
297
+ yield entry
298
+ except Exception as e:
299
+ if self._on_error == "raise":
300
+ raise
301
+ elif self._on_error == "collect":
302
+ log_debug(f"Filter error on {entry}: {e}")
303
+ continue
304
+ else: # skip
305
+ continue
306
+
307
+ def _materialize(self) -> list[Entry]:
308
+ """Internal: builds full list with sort/limit applied."""
309
+ entries = list(self._materialize_iter())
310
+
311
+ # Drop same-path duplicates when .deduplicate() was requested
312
+ if any(getattr(f, "_needs_dedup", False) for f in self._filters):
313
+ entries = _dedupe_entries(entries)
314
+
315
+ # Apply context-aware duplicate/unique filters over ALL entries
316
+ entries = _apply_context_filters(entries, self._filters)
317
+
318
+ # Sort
319
+ if self._sort_key:
320
+ entries = self._sort_entries(entries)
321
+
322
+ # Skip and limit
323
+ if self._skip:
324
+ entries = entries[self._skip :]
325
+ if self._limit is not None:
326
+ entries = entries[: self._limit]
327
+
328
+ return entries
329
+
330
+ def _sort_entries(self, entries: list[Entry]) -> list[Entry]:
331
+ """Sort entries by key."""
332
+ key_func = self._get_sort_key_func()
333
+ reverse = self._sort_desc
334
+ return sorted(entries, key=key_func, reverse=reverse)
335
+
336
+ def _get_sort_key_func(self) -> Callable[[Entry], Any]:
337
+ """Get sort key function."""
338
+ key = self._sort_key
339
+ if key == "name":
340
+ return lambda e: e.name.lower()
341
+ elif key == "size":
342
+ return lambda e: e.size
343
+ elif key == "date" or key == "modified":
344
+ return lambda e: e.modified
345
+ elif key == "created":
346
+ return lambda e: e.created
347
+ elif key == "path":
348
+ return lambda e: str(e.path).lower()
349
+ elif key == "extension":
350
+ return lambda e: e.suffix.lower()
351
+ else:
352
+ return lambda e: str(e.path).lower()
353
+
354
+ # ─── Filter Methods (MODULE 1) ────────────────────────────────────────────
355
+
356
+ def files(self) -> FileChain:
357
+ """Only regular files."""
358
+ from path_file.filters import filter_files
359
+
360
+ return self._with_filter(filter_files())
361
+
362
+ def dirs(self) -> FileChain:
363
+ """Only directories."""
364
+ from path_file.filters import filter_dirs
365
+
366
+ return self._with_filter(filter_dirs())
367
+
368
+ def symlinks(self) -> FileChain:
369
+ """Only symbolic links."""
370
+ from path_file.filters import filter_symlinks
371
+
372
+ return self._with_filter(filter_symlinks())
373
+
374
+ def all(self) -> FileChain:
375
+ """All entries (reset type filter)."""
376
+ from path_file.filters import filter_all
377
+
378
+ return self._with_filter(filter_all())
379
+
380
+ def with_extension(self, ext: str) -> FileChain:
381
+ """Files with specific extension."""
382
+ from path_file.filters import filter_extension
383
+
384
+ return self._with_filter(filter_extension(ext))
385
+
386
+ def with_extensions(self, *exts: str) -> FileChain:
387
+ """Files with any of the given extensions."""
388
+ from path_file.filters import filter_extensions
389
+
390
+ return self._with_filter(filter_extensions(*exts))
391
+
392
+ def without_extension(self, ext: str) -> FileChain:
393
+ """Files NOT having the given extension."""
394
+ from path_file.filters import filter_without_extension
395
+
396
+ return self._with_filter(filter_without_extension(ext))
397
+
398
+ def larger_than(self, size: str | int) -> FileChain:
399
+ """Files larger than given size."""
400
+ from path_file.filters import filter_larger_than
401
+
402
+ return self._with_filter(filter_larger_than(size))
403
+
404
+ def smaller_than(self, size: str | int) -> FileChain:
405
+ """Files smaller than given size."""
406
+ from path_file.filters import filter_smaller_than
407
+
408
+ return self._with_filter(filter_smaller_than(size))
409
+
410
+ def between_sizes(self, min_size: str | int, max_size: str | int) -> FileChain:
411
+ """Files with size between min and max."""
412
+ from path_file.filters import filter_between_sizes
413
+
414
+ return self._with_filter(filter_between_sizes(min_size, max_size))
415
+
416
+ def newer_than(self, duration: str | int) -> FileChain:
417
+ """Modified more recently than duration ago."""
418
+ from path_file.filters import filter_newer_than
419
+
420
+ return self._with_filter(filter_newer_than(_as_duration(duration)))
421
+
422
+ def older_than(self, duration: str | int) -> FileChain:
423
+ """Modified longer ago than duration."""
424
+ from path_file.filters import filter_older_than
425
+
426
+ return self._with_filter(filter_older_than(_as_duration(duration)))
427
+
428
+ def created_newer_than(self, duration: str | int) -> FileChain:
429
+ """Created more recently than duration ago."""
430
+ from path_file.filters import filter_created_newer_than
431
+
432
+ return self._with_filter(filter_created_newer_than(_as_duration(duration)))
433
+
434
+ def created_older_than(self, duration: str | int) -> FileChain:
435
+ """Created longer ago than duration."""
436
+ from path_file.filters import filter_created_older_than
437
+
438
+ return self._with_filter(filter_created_older_than(_as_duration(duration)))
439
+
440
+ def modified_between(self, start: str | datetime, end: str | datetime) -> FileChain:
441
+ """Modified between start and end."""
442
+ from path_file.filters import filter_modified_between
443
+
444
+ return self._with_filter(filter_modified_between(start, end))
445
+
446
+ def created_between(self, start: str | datetime, end: str | datetime) -> FileChain:
447
+ """Created between start and end."""
448
+ from path_file.filters import filter_created_between
449
+
450
+ return self._with_filter(filter_created_between(start, end))
451
+
452
+ def modified_today(self) -> FileChain:
453
+ """Modified today."""
454
+ from path_file.filters import filter_modified_today
455
+
456
+ return self._with_filter(filter_modified_today())
457
+
458
+ def modified_this_week(self) -> FileChain:
459
+ """Modified this week."""
460
+ from path_file.filters import filter_modified_this_week
461
+
462
+ return self._with_filter(filter_modified_this_week())
463
+
464
+ def modified_this_month(self) -> FileChain:
465
+ """Modified this month."""
466
+ from path_file.filters import filter_modified_this_month
467
+
468
+ return self._with_filter(filter_modified_this_month())
469
+
470
+ def created_today(self) -> FileChain:
471
+ """Created today."""
472
+ from path_file.filters import filter_created_today
473
+
474
+ return self._with_filter(filter_created_today())
475
+
476
+ def created_this_week(self) -> FileChain:
477
+ """Created this week."""
478
+ from path_file.filters import filter_created_this_week
479
+
480
+ return self._with_filter(filter_created_this_week())
481
+
482
+ def name_matches(self, pattern: str) -> FileChain:
483
+ """Name matches glob pattern."""
484
+ from path_file.filters import filter_name_matches
485
+
486
+ return self._with_filter(filter_name_matches(pattern))
487
+
488
+ def name_matches_regex(self, pattern: str) -> FileChain:
489
+ """Name matches a regular expression pattern."""
490
+ import re as _re
491
+
492
+ compiled = _re.compile(pattern)
493
+
494
+ def _filter(entry: Entry) -> bool:
495
+ return bool(compiled.search(entry.name))
496
+
497
+ return self._with_filter(_filter)
498
+
499
+ def glob(self, pattern: str, case_sensitive: bool = False) -> FileChain:
500
+ """Name/path matches a glob pattern."""
501
+ from path_file.filters import filter_glob
502
+
503
+ return self._with_filter(filter_glob(pattern, case_sensitive))
504
+
505
+ def name_contains(self, text: str, case_sensitive: bool = False) -> FileChain:
506
+ """Name contains text."""
507
+ from path_file.filters import filter_name_contains
508
+
509
+ return self._with_filter(filter_name_contains(text, case_sensitive))
510
+
511
+ def name_starts_with(self, prefix: str, case_sensitive: bool = False) -> FileChain:
512
+ """Name starts with prefix."""
513
+ from path_file.filters import filter_name_starts_with
514
+
515
+ return self._with_filter(filter_name_starts_with(prefix, case_sensitive))
516
+
517
+ def name_ends_with(self, suffix: str, case_sensitive: bool = False) -> FileChain:
518
+ """Name ends with suffix."""
519
+ from path_file.filters import filter_name_ends_with
520
+
521
+ return self._with_filter(filter_name_ends_with(suffix, case_sensitive))
522
+
523
+ def path_contains(self, text: str, case_sensitive: bool = False) -> FileChain:
524
+ """Full path contains text."""
525
+ from path_file.filters import filter_path_contains
526
+
527
+ return self._with_filter(filter_path_contains(text, case_sensitive))
528
+
529
+ def path_matches(self, pattern: str) -> FileChain:
530
+ """Full path matches regex pattern."""
531
+ from path_file.filters import filter_path_matches
532
+
533
+ return self._with_filter(filter_path_matches(pattern))
534
+
535
+ def in_folder(self, folder: str | Path) -> FileChain:
536
+ """Entry is inside given folder."""
537
+ from path_file.filters import filter_in_folder
538
+
539
+ return self._with_filter(filter_in_folder(folder))
540
+
541
+ def not_in_folder(self, folder: str | Path) -> FileChain:
542
+ """Entry is NOT inside given folder."""
543
+ from path_file.filters import filter_not_in_folder
544
+
545
+ return self._with_filter(filter_not_in_folder(folder))
546
+
547
+ def empty(self) -> FileChain:
548
+ """Empty files or directories."""
549
+ from path_file.filters import filter_empty
550
+
551
+ return self._with_filter(filter_empty())
552
+
553
+ def not_empty(self) -> FileChain:
554
+ """Non-empty files or directories."""
555
+ from path_file.filters import filter_not_empty
556
+
557
+ return self._with_filter(filter_not_empty())
558
+
559
+ def hidden(self) -> FileChain:
560
+ """Hidden entries."""
561
+ from path_file.filters import filter_hidden
562
+
563
+ return self._with_filter(filter_hidden())
564
+
565
+ def visible(self) -> FileChain:
566
+ """Visible (non-hidden) entries."""
567
+ from path_file.filters import filter_visible
568
+
569
+ return self._with_filter(filter_visible())
570
+
571
+ def readable(self) -> FileChain:
572
+ """Readable entries."""
573
+ from path_file.filters import filter_readable
574
+
575
+ return self._with_filter(filter_readable())
576
+
577
+ def writable(self) -> FileChain:
578
+ """Writable entries."""
579
+ from path_file.filters import filter_writable
580
+
581
+ return self._with_filter(filter_writable())
582
+
583
+ def executable(self) -> FileChain:
584
+ """Executable entries."""
585
+ from path_file.filters import filter_executable
586
+
587
+ return self._with_filter(filter_executable())
588
+
589
+ def matching_content(self, text: str, encoding: str = "utf-8") -> FileChain:
590
+ """Text file contains given text."""
591
+ from path_file.filters import filter_matching_content
592
+
593
+ return self._with_filter(filter_matching_content(text, encoding))
594
+
595
+ def matching_regex_in_content(self, pattern: str, encoding: str = "utf-8") -> FileChain:
596
+ """Text file content matches regex."""
597
+ from path_file.filters import filter_matching_regex_in_content
598
+
599
+ return self._with_filter(filter_matching_regex_in_content(pattern, encoding))
600
+
601
+ def containing_line(self, text: str, encoding: str = "utf-8") -> FileChain:
602
+ """Text file contains a line with given text."""
603
+ from path_file.filters import filter_containing_line
604
+
605
+ return self._with_filter(filter_containing_line(text, encoding))
606
+
607
+ def containing_lines(self, *texts: str, encoding: str = "utf-8") -> FileChain:
608
+ """Text file contains ALL of the given lines."""
609
+ from path_file.filters import filter_containing_lines
610
+
611
+ return self._with_filter(filter_containing_lines(*texts, encoding=encoding))
612
+
613
+ def duplicates_by_hash(self, algorithm: str = "sha256") -> dict[str, list[Entry]]:
614
+ """
615
+ Find groups of duplicate entries by content hash.
616
+
617
+ Returns:
618
+ Dict mapping hash -> list of Entries (only groups with 2+ files)
619
+ """
620
+ from path_file.hash import find_duplicates
621
+
622
+ return find_duplicates(self.to_list(), algorithm)
623
+
624
+ def unique_by_hash(self) -> FileChain:
625
+ """Entries with unique content (no duplicates)."""
626
+ from path_file.filters import filter_unique_by_hash
627
+
628
+ return self._with_filter(filter_unique_by_hash())
629
+
630
+ def duplicate_content(self, algorithm: str = "sha256") -> FileChain:
631
+ """Keep only entries whose content (hash) appears more than once."""
632
+ from path_file.filters import filter_duplicates_by_hash
633
+
634
+ return self._with_filter(filter_duplicates_by_hash(algorithm))
635
+
636
+ def duplicates_by_name(self) -> dict[str, list[Entry]]:
637
+ """
638
+ Find groups of duplicate entries by file name.
639
+
640
+ Returns:
641
+ Dict mapping name -> list of Entries (only groups with 2+ files)
642
+ """
643
+ from path_file.hash import find_duplicates_by_name
644
+
645
+ return find_duplicates_by_name(self.to_list())
646
+
647
+ def unique_by_name(self) -> FileChain:
648
+ """Entries with unique names."""
649
+ from path_file.filters import filter_unique_by_name
650
+
651
+ return self._with_filter(filter_unique_by_name())
652
+
653
+ def same_size_as(self, path: str | Path) -> FileChain:
654
+ """Entries with same size as reference file."""
655
+ from path_file.filters import filter_same_size_as
656
+
657
+ return self._with_filter(filter_same_size_as(path))
658
+
659
+ def same_content_as(self, path: str | Path) -> FileChain:
660
+ """Entries with same content as reference file."""
661
+ from path_file.filters import filter_same_content_as
662
+
663
+ return self._with_filter(filter_same_content_as(path))
664
+
665
+ def sort_by(self, key: str, desc: bool = False) -> FileChain:
666
+ """Sort by key: name, size, date, created, path, extension."""
667
+ valid_keys = {"name", "size", "date", "modified", "created", "path", "extension"}
668
+ if key not in valid_keys:
669
+ raise ValueError(f"Invalid sort key: {key}. Valid: {valid_keys}")
670
+ return self._with_config(sort_key=key, sort_desc=desc)
671
+
672
+ def reverse(self) -> FileChain:
673
+ """Reverse current sort order."""
674
+ return self._with_config(sort_desc=not self._sort_desc)
675
+
676
+ def limit(self, n: int) -> FileChain:
677
+ """Limit to first n entries."""
678
+ return self._with_config(limit=n)
679
+
680
+ def skip(self, n: int) -> FileChain:
681
+ """Skip first n entries."""
682
+ return self._with_config(skip=n)
683
+
684
+ def slice(self, start: int, stop: int | None = None) -> FileChain:
685
+ """Slice entries (like list slicing)."""
686
+ return self._with_config(skip=start, limit=stop - start if stop else None)
687
+
688
+ def deduplicate(self) -> FileChain:
689
+ """Remove duplicate entries by resolved path (keeps first occurrence)."""
690
+ return self._with_filter(_DedupFilter())
691
+
692
+ # ─── Execution Modifiers (MODULE 3) ───────────────────────────────────────
693
+
694
+ def dry_run(self, enabled: bool = True) -> FileChain:
695
+ """Mark chain as dry-run (no actual changes)."""
696
+ return self._with_config(dry_run=enabled)
697
+
698
+ def parallel(self, workers: int = 8) -> FileChain:
699
+ """Enable parallel execution with given worker count."""
700
+ return self._with_config(parallel=max(1, workers))
701
+
702
+ def progress(self, enabled: bool = True) -> FileChain:
703
+ """Show progress bar during execution."""
704
+ return self._with_config(progress=enabled)
705
+
706
+ def verbose(self, enabled: bool = True) -> FileChain:
707
+ """Enable verbose output."""
708
+ return self._with_config(verbose=enabled)
709
+
710
+ def quiet(self, enabled: bool = True) -> FileChain:
711
+ """Suppress output."""
712
+ return self._with_config(verbose=not enabled)
713
+
714
+ def on_error(self, action: str) -> FileChain:
715
+ """Set error handling: 'raise', 'skip', or 'collect'."""
716
+ if action not in ("raise", "skip", "collect"):
717
+ raise ValueError("on_error must be 'raise', 'skip', or 'collect'")
718
+ return self._with_config(on_error=action)
719
+
720
+ def recursive(self, enabled: bool = True) -> FileChain:
721
+ """Enable/disable recursive directory traversal."""
722
+ return self._with_config(recursive=enabled)
723
+
724
+ def follow_symlinks(self, enabled: bool = True) -> FileChain:
725
+ """Follow symbolic links to directories."""
726
+ return self._with_config(follow_symlinks=enabled)
727
+
728
+ def max_depth(self, depth: int) -> FileChain:
729
+ """Maximum recursion depth."""
730
+ return self._with_config(max_depth=depth)
731
+
732
+ def min_depth(self, depth: int) -> FileChain:
733
+ """Minimum depth before yielding entries."""
734
+ return self._with_config(min_depth=depth)
735
+
736
+ # ─── Materialization Methods (MODULE 3) ───────────────────────────────────
737
+
738
+ def count(self) -> int:
739
+ """Count matching entries."""
740
+ return len(self._materialize())
741
+
742
+ def first(self) -> Entry | None:
743
+ """Get first matching entry."""
744
+ entries = self._materialize()
745
+ return entries[0] if entries else None
746
+
747
+ def last(self) -> Entry | None:
748
+ """Get last matching entry."""
749
+ entries = self._materialize()
750
+ return entries[-1] if entries else None
751
+
752
+ def to_list(self) -> list[Entry]:
753
+ """Get all matching entries as list."""
754
+ return self._materialize()
755
+
756
+ def to_paths(self) -> list[Path]:
757
+ """Get all matching paths."""
758
+ return [e.path for e in self._materialize()]
759
+
760
+ def to_dict(self) -> list[dict[str, Any]]:
761
+ """Get all entries as list of dicts."""
762
+ return [e.as_dict() for e in self._materialize()]
763
+
764
+ def to_json(self, path: str | Path | None = None, indent: int = 2) -> str:
765
+ """Serialize to JSON string (optionally write to file)."""
766
+ data = self.to_dict()
767
+ json_str = json.dumps(data, indent=indent, ensure_ascii=False, default=str)
768
+ if path:
769
+ Path(path).write_text(json_str, encoding="utf-8")
770
+ return json_str
771
+
772
+ def to_csv(self, path: str | Path | None = None) -> str:
773
+ """Serialize to CSV string (optionally write to file)."""
774
+ entries = self._materialize()
775
+ if not entries:
776
+ csv_str = "path,name,size,modified\n"
777
+ else:
778
+ output = io.StringIO()
779
+ writer = csv.writer(output)
780
+ writer.writerow(
781
+ [
782
+ "path",
783
+ "name",
784
+ "stem",
785
+ "suffix",
786
+ "size",
787
+ "size_human",
788
+ "modified",
789
+ "created",
790
+ "is_file",
791
+ "is_dir",
792
+ ]
793
+ )
794
+ for e in entries:
795
+ writer.writerow(
796
+ [
797
+ str(e.path),
798
+ e.name,
799
+ e.stem,
800
+ e.suffix,
801
+ e.size,
802
+ e.size_human,
803
+ e.modified.isoformat(),
804
+ e.created.isoformat(),
805
+ e.is_file,
806
+ e.is_dir,
807
+ ]
808
+ )
809
+ csv_str = output.getvalue()
810
+ if path:
811
+ Path(path).write_text(csv_str, encoding="utf-8")
812
+ return csv_str
813
+
814
+ def to_table(self) -> str:
815
+ """Pretty ASCII table of entries."""
816
+ entries = self._materialize()
817
+ if not entries:
818
+ return "No entries found."
819
+
820
+ lines = []
821
+ lines.append("┌──────────────────────────────┬──────────┬──────────┬────────────────────┐")
822
+ lines.append("│ Name │ Size │ Type │ Modified │")
823
+ lines.append("├──────────────────────────────┼──────────┼──────────┼────────────────────┤")
824
+
825
+ for e in entries:
826
+ name = e.name[:28] + ".." if len(e.name) > 30 else e.name
827
+ size = e.size_human if e.is_file else "-"
828
+ typ = "FILE" if e.is_file else "DIR" if e.is_dir else "LINK"
829
+ mod = e.modified.strftime("%Y-%m-%d %H:%M")
830
+ lines.append(f"│ {name:<30} │ {size:>8} │ {typ:<8} │ {mod} │")
831
+
832
+ lines.append("└──────────────────────────────┴──────────┴──────────┴────────────────────┘")
833
+ lines.append(f"Total: {len(entries)} entries")
834
+ return "\n".join(lines)
835
+
836
+ def report(self) -> Report:
837
+ """Generate aggregate report."""
838
+ entries = self._materialize()
839
+ return self._build_report(entries)
840
+
841
+ def preview(self) -> str:
842
+ """Dry-run preview of pending action."""
843
+ if not self._action_name:
844
+ return "No action pending. Use copy_to(), move_to(), delete(), etc."
845
+ entries = self._materialize()
846
+ if not entries:
847
+ return f"No files to {self._action_name}."
848
+
849
+ lines = [f"DRY RUN: {self._action_name.upper()} {len(entries)} file(s)"]
850
+ for e in entries[:20]:
851
+ lines.append(f" {e.path} ({e.size_human})")
852
+ if len(entries) > 20:
853
+ lines.append(f" ... and {len(entries) - 20} more")
854
+ return "\n".join(lines)
855
+
856
+ def for_each(self, callback: Callable[[Entry], Any]) -> FileChain:
857
+ """Call callback for each entry (side effects)."""
858
+ for entry in self._materialize():
859
+ try:
860
+ callback(entry)
861
+ except Exception as e:
862
+ if self._on_error == "raise":
863
+ raise
864
+ log_debug(f"Callback error on {entry}: {e}")
865
+ return self
866
+
867
+ def map(self, callback: Callable[[Entry], Any]) -> list[Any]:
868
+ """Transform each entry."""
869
+ return [callback(e) for e in self._materialize()]
870
+
871
+ def reduce(self, func: Callable[[Any, Entry], Any], initial: Any) -> Any:
872
+ """Fold entries with function."""
873
+ result = initial
874
+ for entry in self._materialize():
875
+ result = func(result, entry)
876
+ return result
877
+
878
+ def execute(self) -> ActionResult:
879
+ """Execute pending action."""
880
+ if not self._action_name:
881
+ raise PathflowError("No action to execute. Use copy_to(), move_to(), etc.")
882
+ from path_file.actions import execute_action
883
+
884
+ return execute_action(self)
885
+
886
+ # ─── Iterator Protocol ────────────────────────────────────────────────────
887
+
888
+ def __iter__(self) -> Iterator[Entry]:
889
+ # Full pipeline: filters, context filters, dedupe, sort, skip/limit
890
+ return iter(self._materialize())
891
+
892
+ def __len__(self) -> int:
893
+ return self.count()
894
+
895
+ def __repr__(self) -> str:
896
+ n = self.count()
897
+ return f"<FileChain n={n}>"
898
+
899
+ # ─── Internal Report Building ─────────────────────────────────────────────
900
+
901
+ def _build_report(self, entries: list[Entry]) -> Report:
902
+ """Build aggregate report from entries."""
903
+ report = Report()
904
+ report.chain_size = len(entries)
905
+
906
+ if not entries:
907
+ return report
908
+
909
+ report.total_size = sum(e.size for e in entries)
910
+ report.file_count = sum(1 for e in entries if e.is_file)
911
+ report.dir_count = sum(1 for e in entries if e.is_dir)
912
+ report.symlink_count = sum(1 for e in entries if e.is_symlink)
913
+ report.hidden_count = sum(1 for e in entries if e.is_hidden)
914
+ report.empty_count = sum(1 for e in entries if e.is_empty)
915
+
916
+ # By extension
917
+ for e in entries:
918
+ ext = e.suffix or "(none)"
919
+ report.by_extension[ext] = report.by_extension.get(ext, 0) + 1
920
+
921
+ # Size buckets
922
+ buckets = {
923
+ "0 B": (0, 0),
924
+ "1-10 KB": (1, 10 * 1024),
925
+ "10-100 KB": (10 * 1024, 100 * 1024),
926
+ "100 KB - 1 MB": (100 * 1024, 1024 * 1024),
927
+ "1-10 MB": (1024 * 1024, 10 * 1024 * 1024),
928
+ "10-100 MB": (10 * 1024 * 1024, 100 * 1024 * 1024),
929
+ "100 MB - 1 GB": (100 * 1024 * 1024, 1024 * 1024 * 1024),
930
+ "1-10 GB": (1024 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
931
+ "10 GB+": (10 * 1024 * 1024 * 1024, float("inf")),
932
+ }
933
+ for e in entries:
934
+ for bucket, (min_s, max_s) in buckets.items():
935
+ if min_s <= e.size <= max_s:
936
+ report.by_size_bucket[bucket] = report.by_size_bucket.get(bucket, 0) + 1
937
+ break
938
+
939
+ # Extremes
940
+ file_entries = [e for e in entries if e.is_file]
941
+ if file_entries:
942
+ report.largest = max(file_entries, key=lambda e: e.size)
943
+ report.smallest = min(file_entries, key=lambda e: e.size)
944
+
945
+ report.newest = max(entries, key=lambda e: e.modified)
946
+ report.oldest = min(entries, key=lambda e: e.modified)
947
+
948
+ return report
949
+
950
+
951
+ # ──────────────────────────────────────────────────────────────────────────────
952
+ # ACTION METHODS - These set up the action for later execution
953
+ # ──────────────────────────────────────────────────────────────────────────────
954
+
955
+
956
+ # We'll add action methods to FileChain dynamically
957
+ # This avoids circular import with actions.py
958
+ def _add_action_methods() -> None:
959
+ """Add action methods to FileChain class."""
960
+ from path_file.actions import (
961
+ action_archive_to,
962
+ action_chmod,
963
+ action_compress,
964
+ action_copy,
965
+ action_create_dir,
966
+ action_delete,
967
+ action_extract_to,
968
+ action_hash,
969
+ action_move,
970
+ action_open,
971
+ action_read_bytes,
972
+ action_read_text,
973
+ action_rename,
974
+ action_rename_with,
975
+ action_symlink_to,
976
+ action_touch,
977
+ action_trash,
978
+ action_write_bytes,
979
+ action_write_text,
980
+ )
981
+
982
+ actions: dict[str, Callable[..., Any]] = {
983
+ "copy_to": action_copy,
984
+ "move_to": action_move,
985
+ "delete": action_delete,
986
+ "trash": action_trash,
987
+ "rename": action_rename,
988
+ "rename_with": action_rename_with,
989
+ "archive_to": action_archive_to,
990
+ "compress": action_compress,
991
+ "extract_to": action_extract_to,
992
+ "chmod": action_chmod,
993
+ "touch": action_touch,
994
+ "read_text": action_read_text,
995
+ "read_bytes": action_read_bytes,
996
+ "write_text": action_write_text,
997
+ "write_bytes": action_write_bytes,
998
+ "hash": action_hash,
999
+ "open": action_open,
1000
+ "create_dir": action_create_dir,
1001
+ "symlink_to": action_symlink_to,
1002
+ }
1003
+
1004
+ for name, func in actions.items():
1005
+
1006
+ def make_method(
1007
+ action_name: str, action_func: Callable[..., Any]
1008
+ ) -> Callable[..., FileChain]:
1009
+ def method(self: FileChain, *args: Any, **kwargs: Any) -> FileChain:
1010
+ # Extract dry_run from kwargs to pass to _with_config
1011
+ dry_run = kwargs.pop("dry_run", None)
1012
+ chain = self._with_config(
1013
+ action_name=action_name,
1014
+ action_params=kwargs,
1015
+ dry_run=dry_run,
1016
+ )
1017
+ if args:
1018
+ chain._action_params["_args"] = args
1019
+ return chain
1020
+
1021
+ method.__name__ = action_name
1022
+ method.__doc__ = action_func.__doc__
1023
+ return method
1024
+
1025
+ setattr(FileChain, name, make_method(name, func))
1026
+
1027
+
1028
+ _add_action_methods()