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/actions.py ADDED
@@ -0,0 +1,855 @@
1
+ """Action executors for FileChain operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ import shutil
8
+ import threading
9
+ from collections.abc import Callable
10
+ from concurrent.futures import ThreadPoolExecutor, as_completed
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import IO, Any
14
+
15
+ from path_file._internal._log import get_logger, log_debug, log_info
16
+ from path_file._internal._safety import (
17
+ require_confirm_or_dry_run,
18
+ validate_dest,
19
+ )
20
+ from path_file.archive import (
21
+ compress_file,
22
+ create_archive,
23
+ extract_archive,
24
+ )
25
+ from path_file.chain import FileChain
26
+ from path_file.entries import ActionResult, Entry
27
+ from path_file.exceptions import (
28
+ PathflowError,
29
+ )
30
+
31
+ logger = get_logger(__name__)
32
+
33
+
34
+ # ──────────────────────────────────────────────────────────────────────────────
35
+ # MAIN EXECUTION ENTRY POINT
36
+ # ──────────────────────────────────────────────────────────────────────────────
37
+
38
+
39
+ def execute_action(chain: FileChain) -> ActionResult:
40
+ """
41
+ Execute the pending action on a FileChain.
42
+
43
+ This is the main entry point called by FileChain.execute().
44
+ """
45
+ action_name = chain._action_name
46
+ params = dict(chain._action_params) # Make a copy
47
+ pos_args = params.pop("_args", ())
48
+
49
+ if not action_name:
50
+ raise PathflowError("No action specified")
51
+
52
+ # Special handling for archive_to - creates single archive from all entries
53
+ if action_name == "archive_to":
54
+ return _execute_archive_to(chain, params, pos_args)
55
+
56
+ # Map action name to executor
57
+ executors: dict[str, Callable[..., Any]] = {
58
+ "copy_to": _action_copy,
59
+ "move_to": _action_move,
60
+ "delete": _action_delete,
61
+ "trash": _action_trash,
62
+ "rename": _action_rename,
63
+ "rename_with": _action_rename_with,
64
+ "compress": _action_compress,
65
+ "extract_to": _action_extract_to,
66
+ "chmod": _action_chmod,
67
+ "touch": _action_touch,
68
+ "read_text": _action_read_text,
69
+ "read_bytes": _action_read_bytes,
70
+ "write_text": _action_write_text,
71
+ "write_bytes": _action_write_bytes,
72
+ "hash": _action_hash,
73
+ "open": _action_open,
74
+ "create_dir": _action_create_dir,
75
+ "symlink_to": _action_symlink_to,
76
+ }
77
+
78
+ executor = executors.get(action_name)
79
+ if not executor:
80
+ raise PathflowError(f"Unknown action: {action_name}")
81
+
82
+ # Get entries to process
83
+ entries = chain._materialize()
84
+ if not entries:
85
+ # create_dir/touch are useful on paths that do not exist yet
86
+ if action_name in ("create_dir", "touch", "symlink_to") and not chain._dry_run:
87
+ root = chain._source
88
+ if isinstance(root, (str, Path)) and not Path(root).exists():
89
+ target = Path(root)
90
+ if action_name == "create_dir":
91
+ target.mkdir(parents=True, exist_ok=True)
92
+ return ActionResult(action=action_name, count=1)
93
+ if action_name == "touch":
94
+ target.touch()
95
+ return ActionResult(action=action_name, count=1)
96
+ link_target = pos_args[0] if pos_args else params.get("target")
97
+ if link_target is not None:
98
+ target.symlink_to(Path(link_target))
99
+ return ActionResult(action=action_name, count=1)
100
+ log_info(f"No files to {action_name}")
101
+ return ActionResult(action=action_name, count=0, dry_run=chain._dry_run or False)
102
+
103
+ # Determine dry_run mode
104
+ dry_run = chain._dry_run
105
+ if dry_run is None:
106
+ # Default: dry_run for most destructive ops, but delete/trash require explicit confirm
107
+ dry_run = action_name in ("move_to", "rename", "chmod", "write_text", "write_bytes")
108
+
109
+ # Confirm destructive operations - delete/trash require explicit confirm
110
+ if action_name in ("delete", "trash"):
111
+ if dry_run:
112
+ # In dry_run mode, no confirm needed
113
+ pass
114
+ else:
115
+ # Not in dry_run - require confirm
116
+ require_confirm_or_dry_run(
117
+ action_name,
118
+ len(entries),
119
+ sum(e.size for e in entries),
120
+ params.get("confirm", False),
121
+ dry_run,
122
+ )
123
+
124
+ # Progress bar setup
125
+ progress_bar = None
126
+ if chain._progress and entries:
127
+ from path_file.progress import ProgressBar
128
+
129
+ progress_bar = ProgressBar(len(entries), prefix=f"{action_name}: ")
130
+ progress_bar.__enter__()
131
+
132
+ try:
133
+ # Remove dry_run from params if present (passed explicitly)
134
+ params.pop("dry_run", None)
135
+
136
+ # Execute based on parallel setting
137
+ if chain._parallel > 1 and action_name not in ("read_text", "read_bytes", "hash", "open"):
138
+ result = _execute_parallel(
139
+ executor,
140
+ entries,
141
+ params,
142
+ chain._parallel,
143
+ chain._on_error,
144
+ dry_run,
145
+ action_name,
146
+ progress_bar,
147
+ chain._verbose,
148
+ pos_args,
149
+ )
150
+ else:
151
+ result = _execute_sequential(
152
+ executor,
153
+ entries,
154
+ params,
155
+ chain._on_error,
156
+ dry_run,
157
+ action_name,
158
+ progress_bar,
159
+ chain._verbose,
160
+ pos_args,
161
+ )
162
+
163
+ if progress_bar:
164
+ progress_bar.finish()
165
+ progress_bar.__exit__(None, None, None)
166
+
167
+ return result
168
+
169
+ except Exception as e:
170
+ if progress_bar:
171
+ progress_bar.__exit__(type(e), e, e.__traceback__)
172
+ raise
173
+
174
+
175
+ # ──────────────────────────────────────────────────────────────────────────────
176
+ # EXECUTION HELPERS
177
+ # ──────────────────────────────────────────────────────────────────────────────
178
+
179
+
180
+ def _execute_sequential(
181
+ executor: Callable[..., Any],
182
+ entries: list[Entry],
183
+ params: dict[str, Any],
184
+ on_error: str,
185
+ dry_run: bool,
186
+ action_name: str,
187
+ progress_bar: Any,
188
+ verbose: bool,
189
+ pos_args: tuple[Any, ...] = (),
190
+ ) -> ActionResult:
191
+ """Execute action sequentially."""
192
+ errors: list[tuple[Path, Exception]] = []
193
+ count = 0
194
+ total_size = 0
195
+ skipped = 0
196
+
197
+ for entry in entries:
198
+ try:
199
+ if verbose:
200
+ log_info(f"{action_name}: {entry.path}")
201
+
202
+ executor(entry, *pos_args, dry_run=dry_run, **params)
203
+ count += 1
204
+ if hasattr(entry, "size"):
205
+ total_size += entry.size
206
+
207
+ if progress_bar:
208
+ progress_bar.update(1)
209
+
210
+ except Exception as e:
211
+ if on_error == "raise":
212
+ raise
213
+ elif on_error == "collect":
214
+ errors.append((entry.path, e))
215
+ skipped += 1
216
+ else: # skip
217
+ skipped += 1
218
+ log_debug(f"Skipped {entry.path}: {e}")
219
+
220
+ if progress_bar:
221
+ progress_bar.update(1)
222
+
223
+ return ActionResult(
224
+ action=action_name,
225
+ count=count,
226
+ total_size=total_size,
227
+ duration=0.0, # Will be set by caller
228
+ errors=errors,
229
+ skipped=skipped,
230
+ dry_run=dry_run,
231
+ )
232
+
233
+
234
+ def _execute_parallel(
235
+ executor: Callable[..., Any],
236
+ entries: list[Entry],
237
+ params: dict[str, Any],
238
+ workers: int,
239
+ on_error: str,
240
+ dry_run: bool,
241
+ action_name: str,
242
+ progress_bar: Any,
243
+ verbose: bool,
244
+ pos_args: tuple[Any, ...] = (),
245
+ ) -> ActionResult:
246
+ """Execute action in parallel using thread pool."""
247
+ errors: list[tuple[Path, Exception]] = []
248
+ count = 0
249
+ total_size = 0
250
+ skipped = 0
251
+ lock = threading.Lock()
252
+
253
+ def process_entry(entry: Entry) -> tuple[bool, int, Exception | None]:
254
+ """Process single entry, return (success, size, error)."""
255
+ try:
256
+ if verbose:
257
+ log_info(f"{action_name}: {entry.path}")
258
+ executor(entry, *pos_args, dry_run=dry_run, **params)
259
+ return True, entry.size if entry.is_file else 0, None
260
+ except Exception as e:
261
+ return False, 0, e
262
+
263
+ with ThreadPoolExecutor(max_workers=workers) as executor_pool:
264
+ futures = {executor_pool.submit(process_entry, entry): entry for entry in entries}
265
+
266
+ for future in as_completed(futures):
267
+ entry = futures[future]
268
+ try:
269
+ success, size, error = future.result()
270
+ if success:
271
+ with lock:
272
+ count += 1
273
+ total_size += size
274
+ else:
275
+ with lock:
276
+ if error is not None:
277
+ if on_error == "collect":
278
+ errors.append((entry.path, error))
279
+ skipped += 1
280
+ if on_error == "raise":
281
+ raise error
282
+ except Exception as e:
283
+ if on_error == "raise":
284
+ raise
285
+ with lock:
286
+ if on_error == "collect":
287
+ errors.append((entry.path, e))
288
+ skipped += 1
289
+
290
+ if progress_bar:
291
+ progress_bar.update(1)
292
+
293
+ return ActionResult(
294
+ action=action_name,
295
+ count=count,
296
+ total_size=total_size,
297
+ duration=0.0,
298
+ errors=errors,
299
+ skipped=skipped,
300
+ dry_run=dry_run,
301
+ )
302
+
303
+
304
+ def _execute_archive_to(
305
+ chain: FileChain, params: dict[str, Any], pos_args: tuple[Any, ...]
306
+ ) -> ActionResult:
307
+ """Execute archive_to action - creates single archive from all entries."""
308
+
309
+ entries = chain._materialize()
310
+ if not entries:
311
+ return ActionResult(action="archive_to", count=0, dry_run=chain._dry_run or False)
312
+
313
+ dry_run = chain._dry_run
314
+ if dry_run is None:
315
+ dry_run = False # archive is not destructive
316
+
317
+ if dry_run:
318
+ return ActionResult(action="archive_to", count=len(entries), dry_run=True)
319
+
320
+ archive_path = pos_args[0] if pos_args else params.get("archive_path")
321
+ if not archive_path:
322
+ raise PathflowError("archive_to requires destination archive path")
323
+
324
+ format = params.get("format", "zip")
325
+ compression = params.get("compression", "deflated")
326
+ compression_level = params.get("compression_level", 6)
327
+
328
+ create_archive(entries, Path(archive_path), format, compression, compression_level)
329
+
330
+ total_size = sum(e.size for e in entries if e.is_file)
331
+ return ActionResult(
332
+ action="archive_to",
333
+ count=len(entries),
334
+ total_size=total_size,
335
+ dry_run=False,
336
+ )
337
+
338
+
339
+ # ──────────────────────────────────────────────────────────────────────────────
340
+ # INDIVIDUAL ACTION EXECUTORS
341
+ # ──────────────────────────────────────────────────────────────────────────────
342
+
343
+
344
+ def _action_copy(
345
+ entry: Entry,
346
+ dest: str | Path,
347
+ overwrite: bool = False,
348
+ preserve_metadata: bool = True,
349
+ create_dest: bool = True,
350
+ dry_run: bool = False,
351
+ **kwargs: Any,
352
+ ) -> None:
353
+ """Copy file or directory to destination.
354
+
355
+ If dest is an existing directory (or parent exists and dest doesn't),
356
+ copy the file into that directory preserving the filename.
357
+ """
358
+ if dry_run:
359
+ return
360
+
361
+ dest = Path(dest)
362
+
363
+ # If dest is an existing directory, or parent exists but dest doesn't,
364
+ # treat dest as a directory and copy file into it
365
+ if dest.exists() and dest.is_dir():
366
+ target = dest / entry.path.name
367
+ elif not dest.exists() and dest.parent.exists():
368
+ # Dest doesn't exist but parent does - treat as directory target
369
+ target = dest / entry.path.name
370
+ else:
371
+ target = dest
372
+
373
+ validate_dest(target, create=create_dest, overwrite=overwrite)
374
+
375
+ if entry.is_dir:
376
+ shutil.copytree(entry.path, target, dirs_exist_ok=overwrite)
377
+ if preserve_metadata:
378
+ shutil.copystat(entry.path, target)
379
+ else:
380
+ target.parent.mkdir(parents=True, exist_ok=True)
381
+ shutil.copy2(entry.path, target) if preserve_metadata else shutil.copy(entry.path, target)
382
+
383
+
384
+ def _action_move(
385
+ entry: Entry,
386
+ dest: str | Path,
387
+ overwrite: bool = False,
388
+ create_dest: bool = True,
389
+ dry_run: bool = False,
390
+ **kwargs: Any,
391
+ ) -> None:
392
+ """Move file or directory to destination.
393
+
394
+ If dest is an existing directory, move the file into that directory.
395
+ """
396
+ if dry_run:
397
+ return
398
+
399
+ dest = Path(dest)
400
+
401
+ # If dest is an existing directory, move into it
402
+ if (dest.exists() and dest.is_dir()) or (not dest.exists() and dest.parent.exists()):
403
+ target = dest / entry.path.name
404
+ else:
405
+ target = dest
406
+
407
+ validate_dest(target, create=create_dest, overwrite=overwrite)
408
+ target.parent.mkdir(parents=True, exist_ok=True)
409
+ shutil.move(str(entry.path), str(target))
410
+
411
+
412
+ def _action_delete(
413
+ entry: Entry,
414
+ dry_run: bool = True,
415
+ confirm: bool = False,
416
+ **kwargs: Any,
417
+ ) -> None:
418
+ """Delete file or directory (permanent)."""
419
+ if dry_run:
420
+ return
421
+
422
+ if entry.is_dir:
423
+ shutil.rmtree(entry.path)
424
+ else:
425
+ entry.path.unlink()
426
+
427
+
428
+ def _action_trash(
429
+ entry: Entry,
430
+ dry_run: bool = True,
431
+ confirm: bool = False,
432
+ **kwargs: Any,
433
+ ) -> None:
434
+ """Move file or directory to OS recycle bin/trash."""
435
+ if dry_run:
436
+ return
437
+
438
+ try:
439
+ import send2trash
440
+
441
+ send2trash.send2trash(str(entry.path))
442
+ except ImportError:
443
+ # Fallback: move to ~/.local/share/Trash or Windows Recycle Bin
444
+ _move_to_trash_fallback(entry.path)
445
+
446
+
447
+ def _move_to_trash_fallback(path: Path) -> None:
448
+ """Fallback trash implementation without send2trash."""
449
+ import platform
450
+
451
+ system = platform.system()
452
+
453
+ if system == "Windows":
454
+ # Use Windows Shell API via ctypes
455
+ try:
456
+ import ctypes
457
+ from ctypes import wintypes
458
+
459
+ # Win32 SHFileOperation flag values (kept uppercase-free per PEP 8)
460
+ fo_delete = 3
461
+ fof_allowundo = 0x40
462
+ fof_noconfirmation = 0x10
463
+ fof_silent = 0x4
464
+ fof_noerrorui = 0x400
465
+
466
+ class SHFILEOPSTRUCT(ctypes.Structure):
467
+ _fields_ = [
468
+ ("hwnd", wintypes.HWND),
469
+ ("wFunc", wintypes.UINT),
470
+ ("pFrom", wintypes.LPCWSTR),
471
+ ("pTo", wintypes.LPCWSTR),
472
+ ("fFlags", wintypes.USHORT),
473
+ ("fAnyOperationsAborted", wintypes.BOOL),
474
+ ("hNameMappings", wintypes.LPVOID),
475
+ ("lpszProgressTitle", wintypes.LPCWSTR),
476
+ ]
477
+
478
+ sh_file_operation = ctypes.windll.shell32.SHFileOperationW
479
+ sh_file_operation.argtypes = [ctypes.POINTER(SHFILEOPSTRUCT)]
480
+ sh_file_operation.restype = wintypes.INT
481
+
482
+ op = SHFILEOPSTRUCT()
483
+ op.wFunc = fo_delete
484
+ op.pFrom = str(path.resolve()) + "\0\0"
485
+ op.fFlags = fof_allowundo | fof_noconfirmation | fof_silent | fof_noerrorui
486
+ result = sh_file_operation(ctypes.byref(op))
487
+ if result != 0:
488
+ raise OSError(f"SHFileOperation failed with code {result}")
489
+ return
490
+ except Exception as exc:
491
+ logger.debug("Recycle bin via SHFileOperation unavailable: %s", exc)
492
+
493
+ # Linux/macOS fallback: ~/.local/share/Trash
494
+ trash_dir = Path.home() / ".local" / "share" / "Trash" / "files"
495
+ trash_dir.mkdir(parents=True, exist_ok=True)
496
+ dest = trash_dir / path.name
497
+ counter = 1
498
+ while dest.exists():
499
+ stem = path.stem
500
+ suffix = path.suffix
501
+ dest = trash_dir / f"{stem} ({counter}){suffix}"
502
+ counter += 1
503
+ shutil.move(str(path), str(dest))
504
+
505
+
506
+ def _action_rename(
507
+ entry: Entry,
508
+ pattern: str,
509
+ dry_run: bool = False,
510
+ **kwargs: Any,
511
+ ) -> None:
512
+ """
513
+ Rename file using pattern.
514
+ Pattern supports: {name}, {stem}, {suffix}, {n}, {n:04d}, {date}, {date:%Y-%m-%d}
515
+ """
516
+ if dry_run:
517
+ return
518
+
519
+ # Simple pattern substitution
520
+ # For more complex patterns, use rename_with
521
+ new_name = pattern
522
+ new_name = new_name.replace("{name}", entry.name)
523
+ new_name = new_name.replace("{stem}", entry.stem)
524
+ new_name = new_name.replace("{suffix}", entry.suffix)
525
+ new_name = new_name.replace("{date}", datetime.now().strftime("%Y-%m-%d"))
526
+
527
+ # Handle {n:04d} style
528
+ def repl(match: re.Match[str]) -> str:
529
+ # This is a simple implementation - in real use, you'd track counter
530
+ return "0001" # Placeholder
531
+
532
+ new_name = re.sub(r"\{n(?::([^}]+))?\}", repl, new_name)
533
+
534
+ new_path = entry.path.parent / new_name
535
+ validate_dest(new_path, overwrite=False)
536
+ entry.path.rename(new_path)
537
+
538
+
539
+ def _action_rename_with(
540
+ entry: Entry,
541
+ func: Callable[[str], str],
542
+ dry_run: bool = False,
543
+ **kwargs: Any,
544
+ ) -> None:
545
+ """Rename using a function: func(stem) -> new_stem."""
546
+ if dry_run:
547
+ return
548
+
549
+ new_stem = func(entry.stem)
550
+ new_name = new_stem + entry.suffix
551
+ new_path = entry.path.parent / new_name
552
+ validate_dest(new_path, overwrite=False)
553
+ entry.path.rename(new_path)
554
+
555
+
556
+ def _action_archive_to(
557
+ entry: Entry,
558
+ archive_path: str | Path,
559
+ format: str = "zip",
560
+ compression: str = "deflated",
561
+ dry_run: bool = False,
562
+ **kwargs: Any,
563
+ ) -> None:
564
+ """Add entry to archive."""
565
+ if dry_run:
566
+ return
567
+
568
+ # This is handled by the archive module at chain level
569
+ # Single entry archive not typical - use chain.archive_to()
570
+ raise PathflowError("Use chain.archive_to() for archiving multiple files")
571
+
572
+
573
+ def _action_compress(
574
+ entry: Entry,
575
+ format: str = "gz",
576
+ dry_run: bool = False,
577
+ **kwargs: Any,
578
+ ) -> None:
579
+ """Compress file."""
580
+ if dry_run:
581
+ return
582
+
583
+ if not entry.is_file:
584
+ raise PathflowError(f"Cannot compress directory: {entry.path}")
585
+
586
+ compress_file(entry.path, format)
587
+
588
+
589
+ def _action_extract_to(
590
+ entry: Entry,
591
+ dest: str | Path,
592
+ dry_run: bool = False,
593
+ **kwargs: Any,
594
+ ) -> None:
595
+ """Extract archive to destination."""
596
+ if dry_run:
597
+ return
598
+
599
+ if not entry.is_file:
600
+ raise PathflowError(f"Cannot extract directory: {entry.path}")
601
+
602
+ extract_archive(entry.path, Path(dest))
603
+
604
+
605
+ def _action_chmod(
606
+ entry: Entry,
607
+ mode: int | str,
608
+ dry_run: bool = False,
609
+ **kwargs: Any,
610
+ ) -> None:
611
+ """Change file permissions."""
612
+ if dry_run:
613
+ return
614
+
615
+ if isinstance(mode, str):
616
+ mode = int(mode, 8)
617
+
618
+ entry.path.chmod(mode)
619
+
620
+
621
+ def _action_touch(
622
+ entry: Entry,
623
+ dry_run: bool = False,
624
+ **kwargs: Any,
625
+ ) -> None:
626
+ """Update modification time (create if not exists)."""
627
+ if dry_run:
628
+ return
629
+
630
+ entry.path.touch(exist_ok=True)
631
+
632
+
633
+ def _action_read_text(
634
+ entry: Entry,
635
+ encoding: str = "utf-8",
636
+ dry_run: bool = False,
637
+ **kwargs: Any,
638
+ ) -> str:
639
+ """Read file as text."""
640
+ return entry.read_text(encoding)
641
+
642
+
643
+ def _action_read_bytes(
644
+ entry: Entry,
645
+ dry_run: bool = False,
646
+ **kwargs: Any,
647
+ ) -> bytes:
648
+ """Read file as bytes."""
649
+ return entry.read_bytes()
650
+
651
+
652
+ def _action_write_text(
653
+ entry: Entry,
654
+ data: str,
655
+ encoding: str = "utf-8",
656
+ dry_run: bool = False,
657
+ **kwargs: Any,
658
+ ) -> None:
659
+ """Write text to file."""
660
+ if dry_run:
661
+ return
662
+
663
+ entry.path.write_text(data, encoding=encoding)
664
+
665
+
666
+ def _action_write_bytes(
667
+ entry: Entry,
668
+ data: bytes,
669
+ dry_run: bool = False,
670
+ **kwargs: Any,
671
+ ) -> None:
672
+ """Write bytes to file."""
673
+ if dry_run:
674
+ return
675
+
676
+ entry.path.write_bytes(data)
677
+
678
+
679
+ def _action_hash(
680
+ entry: Entry,
681
+ algorithm: str = "sha256",
682
+ dry_run: bool = False,
683
+ **kwargs: Any,
684
+ ) -> str:
685
+ """Compute file hash."""
686
+ if not entry.is_file:
687
+ return ""
688
+
689
+ if dry_run:
690
+ return ""
691
+
692
+ h = hashlib.new(algorithm)
693
+ with entry.path.open("rb") as f:
694
+ for chunk in iter(lambda: f.read(65536), b""):
695
+ h.update(chunk)
696
+ return h.hexdigest()
697
+
698
+
699
+ def _action_open(
700
+ entry: Entry,
701
+ mode: str = "r",
702
+ dry_run: bool = False,
703
+ **kwargs: Any,
704
+ ) -> IO[Any]:
705
+ """Open file."""
706
+ if dry_run:
707
+ # Return a dummy file-like object
708
+ import io
709
+
710
+ return io.StringIO()
711
+
712
+ return entry.path.open(mode)
713
+
714
+
715
+ def _action_create_dir(
716
+ entry: Entry,
717
+ mode: int = 0o755,
718
+ dry_run: bool = False,
719
+ **kwargs: Any,
720
+ ) -> None:
721
+ """Create directory (for dir entries)."""
722
+ if dry_run:
723
+ return
724
+
725
+ entry.path.mkdir(mode=mode, parents=True, exist_ok=True)
726
+
727
+
728
+ def _action_symlink_to(
729
+ entry: Entry,
730
+ target: str | Path,
731
+ dry_run: bool = False,
732
+ **kwargs: Any,
733
+ ) -> None:
734
+ """Create symlink at entry pointing to target."""
735
+ if dry_run:
736
+ return
737
+
738
+ target = Path(target)
739
+ entry.path.symlink_to(target)
740
+
741
+
742
+ # ──────────────────────────────────────────────────────────────────────────────
743
+ # CHAIN-LEVEL ACTIONS (operate on all entries)
744
+ # ──────────────────────────────────────────────────────────────────────────────
745
+
746
+
747
+ def action_copy(chain: FileChain, dest: str | Path, **kwargs: Any) -> FileChain:
748
+ """Copy all entries to destination directory."""
749
+ return chain._with_config(action_name="copy_to", action_params={"dest": dest, **kwargs})
750
+
751
+
752
+ def action_move(chain: FileChain, dest: str | Path, **kwargs: Any) -> FileChain:
753
+ """Move all entries to destination directory."""
754
+ return chain._with_config(action_name="move_to", action_params={"dest": dest, **kwargs})
755
+
756
+
757
+ def action_delete(chain: FileChain, **kwargs: Any) -> FileChain:
758
+ """Delete all entries."""
759
+ return chain._with_config(action_name="delete", action_params=kwargs)
760
+
761
+
762
+ def action_trash(chain: FileChain, **kwargs: Any) -> FileChain:
763
+ """Move all entries to trash."""
764
+ return chain._with_config(action_name="trash", action_params=kwargs)
765
+
766
+
767
+ def action_rename(chain: FileChain, pattern: str, **kwargs: Any) -> FileChain:
768
+ """Rename all entries using pattern."""
769
+ return chain._with_config(action_name="rename", action_params={"pattern": pattern, **kwargs})
770
+
771
+
772
+ def action_rename_with(chain: FileChain, func: Callable[[str], str], **kwargs: Any) -> FileChain:
773
+ """Rename all entries using function."""
774
+ return chain._with_config(action_name="rename_with", action_params={"func": func, **kwargs})
775
+
776
+
777
+ def action_archive_to(
778
+ chain: FileChain,
779
+ archive_path: str | Path,
780
+ format: str = "zip",
781
+ compression: str = "deflated",
782
+ **kwargs: Any,
783
+ ) -> FileChain:
784
+ """Archive all entries to a single archive."""
785
+ return chain._with_config(
786
+ action_name="archive_to",
787
+ action_params={
788
+ "archive_path": archive_path,
789
+ "format": format,
790
+ "compression": compression,
791
+ **kwargs,
792
+ },
793
+ )
794
+
795
+
796
+ def action_compress(chain: FileChain, format: str = "gz", **kwargs: Any) -> FileChain:
797
+ """Compress each entry individually."""
798
+ return chain._with_config(action_name="compress", action_params={"format": format, **kwargs})
799
+
800
+
801
+ def action_extract_to(chain: FileChain, dest: str | Path, **kwargs: Any) -> FileChain:
802
+ """Extract all archive entries to destination."""
803
+ return chain._with_config(action_name="extract_to", action_params={"dest": dest, **kwargs})
804
+
805
+
806
+ def action_chmod(chain: FileChain, mode: int | str, **kwargs: Any) -> FileChain:
807
+ """Change permissions of all entries."""
808
+ return chain._with_config(action_name="chmod", action_params={"mode": mode, **kwargs})
809
+
810
+
811
+ def action_touch(chain: FileChain, **kwargs: Any) -> FileChain:
812
+ """Touch all entries."""
813
+ return chain._with_config(action_name="touch", action_params=kwargs)
814
+
815
+
816
+ def action_read_text(chain: FileChain, encoding: str = "utf-8", **kwargs: Any) -> FileChain:
817
+ """Read all entries as text."""
818
+ return chain._with_config(
819
+ action_name="read_text", action_params={"encoding": encoding, **kwargs}
820
+ )
821
+
822
+
823
+ def action_read_bytes(chain: FileChain, **kwargs: Any) -> FileChain:
824
+ """Read all entries as bytes."""
825
+ return chain._with_config(action_name="read_bytes", action_params=kwargs)
826
+
827
+
828
+ def action_write_text(chain: FileChain, data: str, **kwargs: Any) -> FileChain:
829
+ """Write same data to all entries."""
830
+ return chain._with_config(action_name="write_text", action_params={"data": data, **kwargs})
831
+
832
+
833
+ def action_write_bytes(chain: FileChain, data: bytes, **kwargs: Any) -> FileChain:
834
+ """Write same bytes to all entries."""
835
+ return chain._with_config(action_name="write_bytes", action_params={"data": data, **kwargs})
836
+
837
+
838
+ def action_hash(chain: FileChain, algorithm: str = "sha256", **kwargs: Any) -> FileChain:
839
+ """Compute hash for all entries."""
840
+ return chain._with_config(action_name="hash", action_params={"algorithm": algorithm, **kwargs})
841
+
842
+
843
+ def action_open(chain: FileChain, mode: str = "r", **kwargs: Any) -> FileChain:
844
+ """Open all entries."""
845
+ return chain._with_config(action_name="open", action_params={"mode": mode, **kwargs})
846
+
847
+
848
+ def action_create_dir(chain: FileChain, mode: int = 0o755, **kwargs: Any) -> FileChain:
849
+ """Create directories for all entries."""
850
+ return chain._with_config(action_name="create_dir", action_params={"mode": mode, **kwargs})
851
+
852
+
853
+ def action_symlink_to(chain: FileChain, target: str | Path, **kwargs: Any) -> FileChain:
854
+ """Create symlinks for all entries pointing to target."""
855
+ return chain._with_config(action_name="symlink_to", action_params={"target": target, **kwargs})