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/filters.py ADDED
@@ -0,0 +1,654 @@
1
+ """Filter functions for FileChain - each returns a callable (Entry) -> bool."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Callable
7
+ from datetime import datetime, timedelta
8
+ from pathlib import Path
9
+
10
+ from path_file._internal._parsers import _compile_regex, make_glob_filter
11
+ from path_file.entries import Entry
12
+ from path_file.units import parse_duration, parse_size
13
+
14
+ # ──────────────────────────────────────────────────────────────────────────────
15
+ # TYPE ALIASES
16
+ # ──────────────────────────────────────────────────────────────────────────────
17
+
18
+ FilterFunc = Callable[[Entry], bool]
19
+
20
+
21
+ # ──────────────────────────────────────────────────────────────────────────────
22
+ # BASIC TYPE FILTERS
23
+ # ──────────────────────────────────────────────────────────────────────────────
24
+
25
+
26
+ def filter_files() -> FilterFunc:
27
+ """Filter: only regular files."""
28
+
29
+ def _filter(entry: Entry) -> bool:
30
+ return entry.is_file
31
+
32
+ return _filter
33
+
34
+
35
+ def filter_dirs() -> FilterFunc:
36
+ """Filter: only directories."""
37
+
38
+ def _filter(entry: Entry) -> bool:
39
+ return entry.is_dir
40
+
41
+ return _filter
42
+
43
+
44
+ def filter_symlinks() -> FilterFunc:
45
+ """Filter: only symbolic links."""
46
+
47
+ def _filter(entry: Entry) -> bool:
48
+ return entry.is_symlink
49
+
50
+ return _filter
51
+
52
+
53
+ def filter_all() -> FilterFunc:
54
+ """Filter: all entries (no-op)."""
55
+
56
+ def _filter(entry: Entry) -> bool:
57
+ return True
58
+
59
+ return _filter
60
+
61
+
62
+ # ──────────────────────────────────────────────────────────────────────────────
63
+ # EXTENSION FILTERS
64
+ # ──────────────────────────────────────────────────────────────────────────────
65
+
66
+
67
+ def filter_extension(ext: str) -> FilterFunc:
68
+ """Filter: files with specific extension (e.g., '.txt' or 'txt')."""
69
+ ext = ext.lower()
70
+ if not ext.startswith("."):
71
+ ext = "." + ext
72
+
73
+ def _filter(entry: Entry) -> bool:
74
+ return entry.suffix.lower() == ext
75
+
76
+ return _filter
77
+
78
+
79
+ def filter_extensions(*exts: str) -> FilterFunc:
80
+ """Filter: files with any of the given extensions."""
81
+ ext_set = {e.lower() if e.lower().startswith(".") else "." + e.lower() for e in exts}
82
+
83
+ def _filter(entry: Entry) -> bool:
84
+ return entry.suffix.lower() in ext_set
85
+
86
+ return _filter
87
+
88
+
89
+ def filter_without_extension(ext: str) -> FilterFunc:
90
+ """Filter: files NOT having the given extension."""
91
+ ext = ext.lower()
92
+ if not ext.startswith("."):
93
+ ext = "." + ext
94
+
95
+ def _filter(entry: Entry) -> bool:
96
+ return entry.suffix.lower() != ext
97
+
98
+ return _filter
99
+
100
+
101
+ # ──────────────────────────────────────────────────────────────────────────────
102
+ # SIZE FILTERS
103
+ # ──────────────────────────────────────────────────────────────────────────────
104
+
105
+
106
+ def filter_larger_than(size: str | int) -> FilterFunc:
107
+ """Filter: files larger than given size."""
108
+ size_bytes = parse_size(size)
109
+
110
+ def _filter(entry: Entry) -> bool:
111
+ return entry.is_file and entry.size > size_bytes
112
+
113
+ return _filter
114
+
115
+
116
+ def filter_smaller_than(size: str | int) -> FilterFunc:
117
+ """Filter: files smaller than given size."""
118
+ size_bytes = parse_size(size)
119
+
120
+ def _filter(entry: Entry) -> bool:
121
+ return entry.is_file and entry.size < size_bytes
122
+
123
+ return _filter
124
+
125
+
126
+ def filter_between_sizes(min_size: str | int, max_size: str | int) -> FilterFunc:
127
+ """Filter: files with size between min and max (inclusive)."""
128
+ min_bytes = parse_size(min_size)
129
+ max_bytes = parse_size(max_size)
130
+
131
+ if min_bytes > max_bytes:
132
+ min_bytes, max_bytes = max_bytes, min_bytes
133
+
134
+ def _filter(entry: Entry) -> bool:
135
+ return entry.is_file and min_bytes <= entry.size <= max_bytes
136
+
137
+ return _filter
138
+
139
+
140
+ def filter_empty() -> FilterFunc:
141
+ """Filter: empty files or directories."""
142
+
143
+ def _filter(entry: Entry) -> bool:
144
+ return entry.is_empty
145
+
146
+ return _filter
147
+
148
+
149
+ def filter_not_empty() -> FilterFunc:
150
+ """Filter: non-empty files or directories."""
151
+
152
+ def _filter(entry: Entry) -> bool:
153
+ return not entry.is_empty
154
+
155
+ return _filter
156
+
157
+
158
+ # ──────────────────────────────────────────────────────────────────────────────
159
+ # TIME FILTERS
160
+ # ──────────────────────────────────────────────────────────────────────────────
161
+
162
+
163
+ def _make_time_filter(
164
+ get_time: Callable[[Entry], datetime],
165
+ duration: str | timedelta,
166
+ newer: bool = True,
167
+ ) -> FilterFunc:
168
+ """Create a time-based filter."""
169
+ delta = parse_duration(duration)
170
+ cutoff = datetime.now() - delta
171
+
172
+ if newer:
173
+
174
+ def _filter(entry: Entry) -> bool:
175
+ return get_time(entry) > cutoff
176
+ else:
177
+
178
+ def _filter(entry: Entry) -> bool:
179
+ return get_time(entry) < cutoff
180
+
181
+ return _filter
182
+
183
+
184
+ def filter_newer_than(duration: str | timedelta) -> FilterFunc:
185
+ """Filter: modified more recently than duration ago."""
186
+ return _make_time_filter(lambda e: e.modified, duration, newer=True)
187
+
188
+
189
+ def filter_older_than(duration: str | timedelta) -> FilterFunc:
190
+ """Filter: modified longer ago than duration."""
191
+ return _make_time_filter(lambda e: e.modified, duration, newer=False)
192
+
193
+
194
+ def filter_created_newer_than(duration: str | timedelta) -> FilterFunc:
195
+ """Filter: created more recently than duration ago."""
196
+ return _make_time_filter(lambda e: e.created, duration, newer=True)
197
+
198
+
199
+ def filter_created_older_than(duration: str | timedelta) -> FilterFunc:
200
+ """Filter: created longer ago than duration."""
201
+ return _make_time_filter(lambda e: e.created, duration, newer=False)
202
+
203
+
204
+ def filter_modified_between(
205
+ start: str | datetime,
206
+ end: str | datetime,
207
+ ) -> FilterFunc:
208
+ """Filter: modified between start and end (inclusive)."""
209
+ from path_file.units import parse_datetime
210
+
211
+ start_dt = parse_datetime(start)
212
+ end_dt = parse_datetime(end)
213
+
214
+ if start_dt > end_dt:
215
+ start_dt, end_dt = end_dt, start_dt
216
+
217
+ def _filter(entry: Entry) -> bool:
218
+ return start_dt <= entry.modified <= end_dt
219
+
220
+ return _filter
221
+
222
+
223
+ def filter_created_between(
224
+ start: str | datetime,
225
+ end: str | datetime,
226
+ ) -> FilterFunc:
227
+ """Filter: created between start and end (inclusive)."""
228
+ from path_file.units import parse_datetime
229
+
230
+ start_dt = parse_datetime(start)
231
+ end_dt = parse_datetime(end)
232
+
233
+ if start_dt > end_dt:
234
+ start_dt, end_dt = end_dt, start_dt
235
+
236
+ def _filter(entry: Entry) -> bool:
237
+ return start_dt <= entry.created <= end_dt
238
+
239
+ return _filter
240
+
241
+
242
+ # Convenience time filters
243
+ def filter_modified_today() -> FilterFunc:
244
+ """Filter: modified today."""
245
+ today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
246
+ tomorrow = today + timedelta(days=1)
247
+
248
+ def _filter(entry: Entry) -> bool:
249
+ return today <= entry.modified < tomorrow
250
+
251
+ return _filter
252
+
253
+
254
+ def filter_modified_this_week() -> FilterFunc:
255
+ """Filter: modified this week (Monday-Sunday)."""
256
+ now = datetime.now()
257
+ week_start = now - timedelta(days=now.weekday())
258
+ week_start = week_start.replace(hour=0, minute=0, second=0, microsecond=0)
259
+ week_end = week_start + timedelta(days=7)
260
+
261
+ def _filter(entry: Entry) -> bool:
262
+ return week_start <= entry.modified < week_end
263
+
264
+ return _filter
265
+
266
+
267
+ def filter_modified_this_month() -> FilterFunc:
268
+ """Filter: modified this month."""
269
+ now = datetime.now()
270
+ month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
271
+ if month_start.month == 12:
272
+ month_end = month_start.replace(year=month_start.year + 1, month=1)
273
+ else:
274
+ month_end = month_start.replace(month=month_start.month + 1)
275
+
276
+ def _filter(entry: Entry) -> bool:
277
+ return month_start <= entry.modified < month_end
278
+
279
+ return _filter
280
+
281
+
282
+ def filter_created_today() -> FilterFunc:
283
+ """Filter: created today."""
284
+ today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
285
+ tomorrow = today + timedelta(days=1)
286
+
287
+ def _filter(entry: Entry) -> bool:
288
+ return today <= entry.created < tomorrow
289
+
290
+ return _filter
291
+
292
+
293
+ def filter_created_this_week() -> FilterFunc:
294
+ """Filter: created this week."""
295
+ now = datetime.now()
296
+ week_start = now - timedelta(days=now.weekday())
297
+ week_start = week_start.replace(hour=0, minute=0, second=0, microsecond=0)
298
+ week_end = week_start + timedelta(days=7)
299
+
300
+ def _filter(entry: Entry) -> bool:
301
+ return week_start <= entry.created < week_end
302
+
303
+ return _filter
304
+
305
+
306
+ # ──────────────────────────────────────────────────────────────────────────────
307
+ # NAME & PATH FILTERS
308
+ # ──────────────────────────────────────────────────────────────────────────────
309
+
310
+
311
+ def filter_name_matches(pattern: str) -> FilterFunc:
312
+ """Filter: name matches regex pattern (full name match)."""
313
+ compiled = _compile_regex(pattern)
314
+
315
+ def _filter(entry: Entry) -> bool:
316
+ return bool(compiled.fullmatch(entry.name))
317
+
318
+ return _filter
319
+
320
+
321
+ def filter_name_contains(text: str, case_sensitive: bool = False) -> FilterFunc:
322
+ """Filter: name contains text."""
323
+ if case_sensitive:
324
+
325
+ def _filter(entry: Entry) -> bool:
326
+ return text in entry.name
327
+ else:
328
+ text_lower = text.lower()
329
+
330
+ def _filter(entry: Entry) -> bool:
331
+ return text_lower in entry.name.lower()
332
+
333
+ return _filter
334
+
335
+
336
+ def filter_name_starts_with(prefix: str, case_sensitive: bool = False) -> FilterFunc:
337
+ """Filter: name starts with prefix."""
338
+ if case_sensitive:
339
+
340
+ def _filter(entry: Entry) -> bool:
341
+ return entry.name.startswith(prefix)
342
+ else:
343
+ prefix_lower = prefix.lower()
344
+
345
+ def _filter(entry: Entry) -> bool:
346
+ return entry.name.lower().startswith(prefix_lower)
347
+
348
+ return _filter
349
+
350
+
351
+ def filter_name_ends_with(suffix: str, case_sensitive: bool = False) -> FilterFunc:
352
+ """Filter: name ends with suffix."""
353
+ if case_sensitive:
354
+
355
+ def _filter(entry: Entry) -> bool:
356
+ return entry.name.endswith(suffix)
357
+ else:
358
+ suffix_lower = suffix.lower()
359
+
360
+ def _filter(entry: Entry) -> bool:
361
+ return entry.name.lower().endswith(suffix_lower)
362
+
363
+ return _filter
364
+
365
+
366
+ def filter_path_contains(text: str, case_sensitive: bool = False) -> FilterFunc:
367
+ """Filter: full path contains text."""
368
+ if case_sensitive:
369
+
370
+ def _filter(entry: Entry) -> bool:
371
+ return text in str(entry.path)
372
+ else:
373
+ text_lower = text.lower()
374
+
375
+ def _filter(entry: Entry) -> bool:
376
+ return text_lower in str(entry.path).lower()
377
+
378
+ return _filter
379
+
380
+
381
+ def filter_path_matches(pattern: str) -> FilterFunc:
382
+ """Filter: full path matches regex pattern."""
383
+ compiled = _compile_regex(pattern)
384
+
385
+ def _filter(entry: Entry) -> bool:
386
+ return bool(compiled.search(str(entry.path)))
387
+
388
+ return _filter
389
+
390
+
391
+ def filter_in_folder(folder: str | Path) -> FilterFunc:
392
+ """Filter: entry is inside given folder (or subfolder)."""
393
+ folder_path = Path(folder).resolve()
394
+
395
+ def _filter(entry: Entry) -> bool:
396
+ try:
397
+ entry.path.relative_to(folder_path)
398
+ return True
399
+ except ValueError:
400
+ return False
401
+
402
+ return _filter
403
+
404
+
405
+ def filter_not_in_folder(folder: str | Path) -> FilterFunc:
406
+ """Filter: entry is NOT inside given folder."""
407
+ folder_path = Path(folder).resolve()
408
+
409
+ def _filter(entry: Entry) -> bool:
410
+ try:
411
+ entry.path.relative_to(folder_path)
412
+ return False
413
+ except ValueError:
414
+ return True
415
+
416
+ return _filter
417
+
418
+
419
+ # ──────────────────────────────────────────────────────────────────────────────
420
+ # VISIBILITY & PERMISSION FILTERS
421
+ # ──────────────────────────────────────────────────────────────────────────────
422
+
423
+
424
+ def filter_hidden() -> FilterFunc:
425
+ """Filter: hidden files/directories."""
426
+
427
+ def _filter(entry: Entry) -> bool:
428
+ return entry.is_hidden
429
+
430
+ return _filter
431
+
432
+
433
+ def filter_visible() -> FilterFunc:
434
+ """Filter: non-hidden files/directories."""
435
+
436
+ def _filter(entry: Entry) -> bool:
437
+ return not entry.is_hidden
438
+
439
+ return _filter
440
+
441
+
442
+ def filter_readable() -> FilterFunc:
443
+ """Filter: readable entries."""
444
+
445
+ def _filter(entry: Entry) -> bool:
446
+ return os.access(entry.path, os.R_OK)
447
+
448
+ return _filter
449
+
450
+
451
+ def filter_writable() -> FilterFunc:
452
+ """Filter: writable entries."""
453
+
454
+ def _filter(entry: Entry) -> bool:
455
+ return os.access(entry.path, os.W_OK)
456
+
457
+ return _filter
458
+
459
+
460
+ def filter_executable() -> FilterFunc:
461
+ """Filter: executable entries."""
462
+
463
+ def _filter(entry: Entry) -> bool:
464
+ return os.access(entry.path, os.X_OK)
465
+
466
+ return _filter
467
+
468
+
469
+ # ──────────────────────────────────────────────────────────────────────────────
470
+ # CONTENT FILTERS
471
+ # ──────────────────────────────────────────────────────────────────────────────
472
+
473
+
474
+ def filter_matching_content(text: str, encoding: str = "utf-8") -> FilterFunc:
475
+ """Filter: text file contains given text."""
476
+
477
+ def _filter(entry: Entry) -> bool:
478
+ if not entry.is_file:
479
+ return False
480
+ try:
481
+ content = entry.read_text(encoding)
482
+ return text in content
483
+ except (UnicodeDecodeError, OSError):
484
+ return False
485
+
486
+ return _filter
487
+
488
+
489
+ def filter_matching_regex_in_content(pattern: str, encoding: str = "utf-8") -> FilterFunc:
490
+ """Filter: text file content matches regex pattern."""
491
+ compiled = _compile_regex(pattern)
492
+
493
+ def _filter(entry: Entry) -> bool:
494
+ if not entry.is_file:
495
+ return False
496
+ try:
497
+ content = entry.read_text(encoding)
498
+ return bool(compiled.search(content))
499
+ except (UnicodeDecodeError, OSError):
500
+ return False
501
+
502
+ return _filter
503
+
504
+
505
+ def filter_containing_line(text: str, encoding: str = "utf-8") -> FilterFunc:
506
+ """Filter: text file contains a line with given text."""
507
+
508
+ def _filter(entry: Entry) -> bool:
509
+ if not entry.is_file:
510
+ return False
511
+ try:
512
+ content = entry.read_text(encoding)
513
+ return any(text in line for line in content.splitlines())
514
+ except (UnicodeDecodeError, OSError):
515
+ return False
516
+
517
+ return _filter
518
+
519
+
520
+ def filter_containing_lines(*texts: str, encoding: str = "utf-8") -> FilterFunc:
521
+ """Filter: text file contains ALL of the given lines."""
522
+
523
+ def _filter(entry: Entry) -> bool:
524
+ if not entry.is_file:
525
+ return False
526
+ try:
527
+ content = entry.read_text(encoding)
528
+ lines = content.splitlines()
529
+ return all(any(t in line for line in lines) for t in texts)
530
+ except (UnicodeDecodeError, OSError):
531
+ return False
532
+
533
+ return _filter
534
+
535
+
536
+ # ──────────────────────────────────────────────────────────────────────────────
537
+ # DUPLICATE FILTERS
538
+ # ──────────────────────────────────────────────────────────────────────────────
539
+
540
+
541
+ class _ContextFilter:
542
+ """
543
+ Callable marker for context-aware (duplicate/unique) filters.
544
+
545
+ These filters need the full entry list to work, so per-entry calls always
546
+ pass through (return True) and the real decision is made by the chain in
547
+ ``FileChain._materialize()`` based on ``mode``.
548
+ """
549
+
550
+ _needs_context: bool = True
551
+
552
+ def __init__(self, mode: str, algorithm: str | None = None) -> None:
553
+ self.mode = mode
554
+ self._algorithm = algorithm
555
+
556
+ def __call__(self, entry: Entry) -> bool:
557
+ return True # marker only; the chain applies the real decision
558
+
559
+
560
+ def filter_duplicates_by_hash(algorithm: str = "sha256") -> FilterFunc:
561
+ """Filter: entries that have duplicate content (by hash)."""
562
+ # Context-aware filter; the chain applies it against all entries.
563
+ return _ContextFilter("duplicates_by_hash", algorithm)
564
+
565
+
566
+ def filter_unique_by_hash() -> FilterFunc:
567
+ """Filter: entries with unique content (no duplicates)."""
568
+ # Context-aware filter; the chain applies it against all entries.
569
+ return _ContextFilter("unique_by_hash")
570
+
571
+
572
+ def filter_duplicates_by_name() -> FilterFunc:
573
+ """Filter: entries with duplicate names."""
574
+ # Context-aware filter; the chain applies it against all entries.
575
+ return _ContextFilter("duplicates_by_name")
576
+
577
+
578
+ def filter_unique_by_name() -> FilterFunc:
579
+ """Filter: entries with unique names."""
580
+ # Context-aware filter; the chain applies it against all entries.
581
+ return _ContextFilter("unique_by_name")
582
+
583
+
584
+ def filter_same_size_as(path: str | Path) -> FilterFunc:
585
+ """Filter: entries with same size as reference file."""
586
+ ref_path = Path(path).resolve()
587
+ ref_size = ref_path.stat().st_size if ref_path.exists() else -1
588
+
589
+ def _filter(entry: Entry) -> bool:
590
+ return entry.is_file and entry.size == ref_size
591
+
592
+ return _filter
593
+
594
+
595
+ def filter_same_content_as(path: str | Path) -> FilterFunc:
596
+ """Filter: entries with same content as reference file."""
597
+ ref_path = Path(path).resolve()
598
+ ref_hash = ""
599
+ if ref_path.exists() and ref_path.is_file():
600
+ import hashlib
601
+
602
+ h = hashlib.sha256()
603
+ with ref_path.open("rb") as f:
604
+ for chunk in iter(lambda: f.read(65536), b""):
605
+ h.update(chunk)
606
+ ref_hash = h.hexdigest()
607
+
608
+ def _filter(entry: Entry) -> bool:
609
+ return entry.is_file and entry.hash_sha256 == ref_hash
610
+
611
+ return _filter
612
+
613
+
614
+ # ──────────────────────────────────────────────────────────────────────────────
615
+ # GLOB FILTER (convenience)
616
+ # ──────────────────────────────────────────────────────────────────────────────
617
+
618
+
619
+ def filter_glob(pattern: str, case_sensitive: bool = False) -> FilterFunc:
620
+ """Filter: name matches glob pattern."""
621
+ matcher = make_glob_filter(pattern, case_sensitive)
622
+
623
+ def _filter(entry: Entry) -> bool:
624
+ return matcher(entry.name) or matcher(str(entry.path))
625
+
626
+ return _filter
627
+
628
+
629
+ # ──────────────────────────────────────────────────────────────────────────────
630
+ # COMBINATION HELPERS
631
+ # ──────────────────────────────────────────────────────────────────────────────
632
+
633
+
634
+ def combine_filters(*filters: FilterFunc, operator: str = "and") -> FilterFunc:
635
+ """Combine multiple filters with AND or OR logic."""
636
+ if operator.lower() == "or":
637
+
638
+ def _filter(entry: Entry) -> bool:
639
+ return any(f(entry) for f in filters)
640
+ else: # "and"
641
+
642
+ def _filter(entry: Entry) -> bool:
643
+ return all(f(entry) for f in filters)
644
+
645
+ return _filter
646
+
647
+
648
+ def negate_filter(filter_func: FilterFunc) -> FilterFunc:
649
+ """Negate a filter."""
650
+
651
+ def _filter(entry: Entry) -> bool:
652
+ return not filter_func(entry)
653
+
654
+ return _filter