-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackcopy.py
More file actions
executable file
·2600 lines (2273 loc) · 101 KB
/
stackcopy.py
File metadata and controls
executable file
·2600 lines (2273 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# SPDX-License-Identifier: MIT
# Stackcopy version 1.5.4 by Alan Rockefeller
# 4/11/26
# Copies / renames only the photos that have been stacked in-camera - designed for Olympus / OM System, though it might work for other cameras too.
# Works on Linux, WSL, and Windows.
from __future__ import annotations
import sys
import os
import platform
import shutil
import uuid
import time
import argparse
import re
import errno
from bisect import bisect_left
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from datetime import datetime, date, timedelta
from typing import Any
# ---------------------------------------------------------------------------
# Platform helpers
# ---------------------------------------------------------------------------
def _is_wsl() -> bool:
"""Detect if running under Windows Subsystem for Linux."""
try:
with open("/proc/version", "r") as f:
return "microsoft" in f.read().lower()
except (OSError, IOError):
return False
IS_WINDOWS = platform.system() == "Windows"
IS_WSL = _is_wsl()
_wsl_warning_shown = False
def _is_wsl_cross_fs(path: str) -> bool:
"""Return True if *path* lives on a Windows volume accessed through WSL's
/mnt/ bridge (e.g. /mnt/c/..., /mnt/e/...). These paths go through the
9P file-system driver and are dramatically slower than native ext4."""
if not IS_WSL:
return False
abspath = os.path.abspath(path)
return bool(re.match(r"^/mnt/[a-zA-Z]/", abspath))
def _warn_wsl_performance(paths: list[str], operation_desc: str) -> None:
"""Print a one-time warning when WSL cross-filesystem paths are involved."""
global _wsl_warning_shown
if _wsl_warning_shown:
return
cross = [p for p in paths if _is_wsl_cross_fs(p)]
if not cross:
return
_wsl_warning_shown = True
prefixes: set[str] = set()
for p in cross:
parts = os.path.abspath(p).split("/")
prefixes.add("/".join(parts[:4]))
print(
f"\nPerformance warning: This {operation_desc} operation involves path(s) on a\n"
f" Windows filesystem accessed via WSL's /mnt/ bridge, which is significantly\n"
f" slower than native Linux filesystems due to 9P protocol overhead."
)
for pfx in sorted(prefixes):
print(f" {pfx}/...")
print(
"\n Tips to improve speed:\n"
" - Copy files to a native Linux path (e.g. ~/photos/) before processing\n"
" - Or run stackcopy natively on Windows: python stackcopy.py ...\n"
" See: https://learn.microsoft.com/en-us/windows/wsl/filesystems\n"
)
def _default_pictures_dir() -> str:
"""Return the user's Pictures directory, respecting platform conventions."""
if IS_WINDOWS:
try:
import ctypes
import ctypes.wintypes
CSIDL_MYPICTURES = 0x0027
buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
# Fetch the path and check HRESULT (0 == S_OK)
hresult = ctypes.windll.shell32.SHGetFolderPathW(
None, CSIDL_MYPICTURES, None, 0, buf
)
if hresult == 0:
if buf.value:
return buf.value
except (ImportError, AttributeError):
pass
# On Linux/WSL, prefer ~/pictures if it exists (common convention),
# otherwise fall back to ~/Pictures.
home = os.path.expanduser("~")
lowercase = os.path.join(home, "pictures")
if os.path.exists(lowercase):
return lowercase
return os.path.join(home, "Pictures")
# ---------------------------------------------------------------------------
# Default paths — override with environment variables if needed:
# STACKCOPY_STACK_INPUT_DIR — where stack input photos go
# STACKCOPY_LIGHTROOM_IMPORT_DIR — where stacked outputs and remaining files go
# ---------------------------------------------------------------------------
_env_stack_input = os.environ.get("STACKCOPY_STACK_INPUT_DIR")
if _env_stack_input:
STACK_INPUT_DIR = os.path.abspath(os.path.expanduser(_env_stack_input))
else:
STACK_INPUT_DIR = os.path.join(_default_pictures_dir(), "olympus.stack.input.photos")
# Regex to identify numeric stems for sequence grouping.
# It assumes numeric parts are 6 or more digits, common for Olympus/OM System in-camera stacking.
# Stems with fewer digits (e.g., 4-digit counters) will not be treated as numeric sequences.
NUMERIC_STEM_REGEX = re.compile(r"([a-zA-Z0-9_-]*)(\d{6,})")
@dataclass
class PlannedMove:
"""A single file move operation planned during --lightroomimport."""
src_path: str
dest_path: str # final destination (single move, no intermediate steps)
category: str # "stack_output", "stack_input", "remaining"
stem: str
file_type: str # "jpg" or "raw"
mtime: datetime | None
basename_orig: str # original filename
basename_dest: (
str # destination filename (may include "stacked" rename + collision suffix)
)
dest_dir: str
def get_file_mtime(file_record, verbose=False):
"""Lazily fetch mtime, caching the result."""
if file_record.get("mtime") is not None:
return file_record["mtime"]
if "entry" in file_record:
try:
stat_info = file_record["entry"].stat(follow_symlinks=False)
mtime_dt = datetime.fromtimestamp(stat_info.st_mtime)
file_record["mtime"] = mtime_dt
file_record["date"] = mtime_dt.date()
return mtime_dt
except OSError as e:
if verbose:
print(f"Warning: Could not stat file '{file_record['path']}': {e}")
pass
return None
def get_file_date(file_record, verbose=False):
"""Lazily fetch date, caching the result."""
if file_record.get("date") is not None:
return file_record["date"]
# Calling get_file_mtime will populate both mtime and date
if get_file_mtime(file_record, verbose):
return file_record.get("date")
return None
def get_stem_mtime(record, verbose=False):
"""
Get the mtime for a stem record, preferring RAW over JPG.
Utilizes get_file_mtime to ensure caching and logging.
"""
raw_files = record["files"].get("raw")
if raw_files:
mtime = get_file_mtime(raw_files, verbose)
if mtime:
return mtime
jpg_files = record["files"].get("jpg")
if jpg_files:
mtime = get_file_mtime(jpg_files, verbose)
if mtime:
return mtime
return None
def create_new_filename(stem, ext, prefix=None):
"""Create a new filename with optional prefix and 'stacked' suffix."""
parts = [stem]
if prefix:
# Trim whitespace from prefix to avoid double spaces
prefix = prefix.strip()
if prefix: # Only add if not empty after stripping
parts.append(prefix)
parts.append("stacked")
# Join with single space and collapse any multiple spaces
new_stem = " ".join(parts)
# Collapse multiple spaces into single spaces
new_stem = re.sub(r"\s+", " ", new_stem)
return f"{new_stem}{ext}"
def ensure_directory_once(path, created_cache, dry_run=False):
"""Create a directory only once per execution (no-op during dry runs)."""
if dry_run:
return
norm_path = os.path.abspath(os.path.normpath(path))
if norm_path in created_cache:
return
os.makedirs(norm_path, exist_ok=True)
created_cache.add(norm_path)
def is_already_processed(filename):
"""Check if a file has already been processed (contains 'stacked' as a word)."""
stem, _ext = os.path.splitext(filename)
# Use word boundary regex to match 'stacked' as a complete word
# This will match: "image stacked.jpg", "stacked_image.jpg", "stacked-photo.jpg", etc.
return bool(re.search(r"\bstacked\b", stem.lower()))
def normalize_path(path):
"""Normalize and resolve a path to its absolute form."""
return os.path.abspath(os.path.expanduser(path))
def display_path(path):
"""Format a path for user display, shortening to ~ on non-Windows platforms."""
if os.name == "nt":
return os.path.abspath(path)
home = os.path.expanduser("~")
abspath = os.path.abspath(path)
if abspath == home:
return "~"
prefix = home + os.sep
if abspath.startswith(prefix):
return "~" + os.sep + abspath[len(prefix) :]
return abspath
def paths_are_same(path1, path2):
"""Check if two paths refer to the same location, handling non-existent paths."""
norm_path1 = normalize_path(path1)
norm_path2 = normalize_path(path2)
# If both paths exist, use samefile
if os.path.exists(norm_path1) and os.path.exists(norm_path2):
try:
return os.path.samefile(norm_path1, norm_path2)
except OSError:
return False
# Otherwise, compare normalized paths
return norm_path1 == norm_path2
def files_identical(src_path, dest_path, chunk_size=1024 * 1024):
"""Return True if src and dest have identical content, False otherwise."""
try:
if os.path.getsize(src_path) != os.path.getsize(dest_path):
return False
with open(src_path, "rb") as fsrc, open(dest_path, "rb") as fdst:
while True:
b1 = fsrc.read(chunk_size)
b2 = fdst.read(chunk_size)
if not b1 and not b2:
return True
if b1 != b2:
return False
except OSError:
# If we can't read either file, treat them as non-identical and let the caller decide.
return False
def add_counter_suffix(basename: str, counter: int) -> str:
"""
Insert a counter suffix before the extension: IMG.JPG -> IMG__2.JPG
Counter=1 returns the original basename.
"""
if counter <= 1:
return basename
stem, ext = os.path.splitext(basename)
return f"{stem}__{counter}{ext}"
def dest_conflicts(src_path: str, dest_path: str, force: bool) -> bool:
"""
Return True if dest_path exists and we should NOT overwrite it.
If contents are identical, it's not a conflict (we treat it as safe).
If --force is set, we consider it not a conflict (user explicitly wants overwrite).
"""
if not os.path.exists(dest_path):
return False
if force:
return False
# If source exists and is identical to destination, it's safe to treat as non-conflict.
return not (os.path.exists(src_path) and files_identical(src_path, dest_path))
def pick_unique_basenames_for_stem(
dest_dir: str,
files_by_type: dict[str, Any],
force: bool,
_dry_run: bool,
reserved_paths: set[str] | None = None,
) -> tuple[int, dict[str, str]]:
"""
Choose a single counter for *all* files in this stem (e.g., JPG+ORF) so they stay paired.
Returns (counter, {file_type: chosen_basename}).
Only applies counter suffixing when a destination collision exists and --force is NOT set.
reserved_paths: optional set of destination paths already claimed by earlier planned
moves (used by --lightroomimport plan-then-execute to avoid two planned moves
targeting the same path).
"""
orig = {ft: fi["basename"] for ft, fi in files_by_type.items() if fi}
srcs = {ft: fi["path"] for ft, fi in files_by_type.items() if fi}
# If force is on, do not auto-rename; user asked to overwrite.
if force:
return 1, orig
# Try counters starting at 1 until all destinations are non-conflicting.
# (Hard cap avoids infinite loops in weird cases.)
for counter in range(1, 1000):
chosen = {}
ok = True
for ft, basename in orig.items():
candidate_basename = add_counter_suffix(basename, counter)
candidate_path = os.path.join(dest_dir, candidate_basename)
if dest_conflicts(srcs[ft], candidate_path, force=False):
ok = False
break
if reserved_paths and candidate_path in reserved_paths:
ok = False
break
chosen[ft] = candidate_basename
if ok:
return counter, chosen
# Fallback (extremely unlikely): return the last tried mapping.
return 999, {ft: add_counter_suffix(bn, 999) for ft, bn in orig.items()}
def print_collision_rename_notice(
dest_dir: str, stem_label: str, changes: list[tuple[str, str]], dry_run: bool
) -> None:
"""
Always prints (even without --verbose) when we rename due to destination collisions.
"""
if not changes:
return
verb = "Would rename" if dry_run else "Renaming"
why = (
"a file with the same name already exists in the destination "
"(usually from an earlier import after the camera card counter reset)"
)
print(
f"Note: {verb} files for '{stem_label}' in '{dest_dir}' to avoid overwriting earlier photos ({why})"
)
for old, new in changes:
print(f" - {old} -> {new}")
def _atomic_copy2(src_path: str, dest_path: str) -> None:
"""Copy to a temp file in dest dir, then atomically replace dest_path."""
dest_dir = os.path.dirname(dest_path)
os.makedirs(dest_dir, exist_ok=True)
tmp_path = os.path.join(
dest_dir, f".__stackcopy_tmp__{os.path.basename(dest_path)}.{uuid.uuid4().hex}"
)
try:
shutil.copy2(src_path, tmp_path)
# Atomic replace: dest_path is either old or new, never partial
os.replace(tmp_path, dest_path)
finally:
# Clean up temp if something went wrong before replace
try:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
except OSError:
pass
def safe_file_operation(
operation, src_path, dest_path, operation_name, force=False, dry_run=False
):
"""
Perform a safe file copy or move.
Returns: (success_bool, bytes_copied_count)
"""
# Determine size before operation in case of move/deletion
src_size = 0
if os.path.exists(src_path):
try:
src_size = os.path.getsize(src_path)
except OSError:
pass
# If destination exists and we're not forcing, see if it's identical to the source.
if os.path.exists(dest_path) and not force:
# Check self-heal first (applies to both dry-run and real)
is_self_heal = False
try:
if os.path.exists(src_path):
src_size_curr = os.path.getsize(src_path)
dst_size = os.path.getsize(dest_path)
# Self-heal: if destination is a 0-byte placeholder but source is non-zero
if src_size_curr > 0 and dst_size == 0:
is_self_heal = True
except OSError:
pass
if is_self_heal:
msg = (
"replacing from source" if not dry_run else "would replace from source"
)
print(f"Note: destination '{dest_path}' exists but is 0 bytes; {msg}.")
force = True
elif dry_run:
print(
f"Warning: '{dest_path}' already exists. Would need --force to overwrite."
)
return False, 0
elif os.path.exists(src_path):
# If contents are identical, treat this as success.
if files_identical(src_path, dest_path):
if operation == "move":
try:
os.unlink(src_path)
except OSError as delete_error:
print(
f"Note: destination '{dest_path}' already exists with identical content; "
f"source '{src_path}' could not be deleted: {delete_error}"
)
else:
print(
f"Note: destination '{dest_path}' already exists with identical content; "
f"deleted source '{src_path}'."
)
return True, 0
else:
print(
f"Note: destination '{dest_path}' already exists with identical content; "
f"skipping copy from '{src_path}'."
)
return True, 0
print(f"Warning: '{dest_path}' already exists. Use --force to overwrite.")
return False, 0
else:
print(f"Warning: '{dest_path}' already exists. Use --force to overwrite.")
return False, 0
if dry_run:
return True, 0
try:
if operation == "move":
try:
# Same-filesystem fast path (metadata only)
os.replace(src_path, dest_path)
return True, 0
except OSError as move_error:
if move_error.errno == errno.EXDEV:
# Cross-device: atomic copy then delete source
_atomic_copy2(src_path, dest_path)
try:
os.unlink(src_path)
except OSError as delete_error:
print(
f"Note: {operation_name} '{src_path}' to '{dest_path}' completed, "
f"but source could not be deleted: {delete_error}"
)
# For cross-device moves, bytes were physically moved
return True, src_size
else:
raise
elif operation == "copy":
_atomic_copy2(src_path, dest_path)
return True, src_size
return True, 0
except (OSError, shutil.Error) as e:
print(f"Error {operation_name} '{src_path}' to '{dest_path}': {e}")
return False, 0
def format_bytes(n: int) -> str:
"""Format bytes into human readable string (KiB, MiB, etc)."""
# Special case for bytes to avoid decimals (e.g. "12 B" not "12.0 B")
if abs(n) < 1024:
return f"{int(n)} B"
val = float(n) / 1024.0
for unit in ["KiB", "MiB", "GiB", "TiB"]:
if abs(val) < 1024.0:
return f"{val:3.1f} {unit}"
val /= 1024.0
return f"{val:.1f} PiB"
def get_existing_parent(path: str) -> str | None:
"""Return the nearest existing parent directory for a path."""
try:
path = os.path.abspath(path)
while not os.path.exists(path):
parent = os.path.dirname(path)
if parent == path: # Root reached and doesn't exist? Unlikely.
return None
path = parent
return path
except OSError:
return None
def get_device_id(path: str) -> int | None:
"""Get the device ID for a path, walking up if it doesn't exist."""
existing_path = get_existing_parent(path)
if existing_path:
try:
return os.stat(existing_path).st_dev
except OSError:
return None
return None
def estimate_required_bytes_for_ops(ops: list[tuple[str, str, str]]) -> dict[int, dict]:
"""
Estimate space requirements for operations.
ops: list of (src_path, dest_path, op_type) where op_type is 'move' or 'copy'.
Returns: {device_id: {'bytes': int, 'count': int, 'sample_path': str}}
"""
req_map = defaultdict(lambda: {"bytes": 0, "count": 0, "sample_path": None})
for src_path, dest_path, op_type in ops:
# 1. Get source size and device
try:
src_stat = os.stat(src_path)
src_size = src_stat.st_size
src_dev = src_stat.st_dev
except OSError:
# If source is missing/unreadable, we can't estimate size.
# Treat as 0 bytes to avoid crashing.
src_size = 0
src_dev = None
# 2. Get destination device
dest_dev = get_device_id(dest_path)
if dest_dev is None:
continue
# 3. Determine if this writes to destination
writes_to_dest = False
if op_type == "copy":
writes_to_dest = True
elif op_type == "move" and (src_dev is None or src_dev != dest_dev):
# If we can't determine source device, assume cross-device (safest)
writes_to_dest = True
if writes_to_dest:
info = req_map[dest_dev]
info["bytes"] += src_size
info["count"] += 1
if info["sample_path"] is None:
info["sample_path"] = dest_path
return req_map
# Cache for confirmed filesystems to avoid repeated prompts
_confirmed_filesystems = set()
def confirm_if_low_space(ops: list[tuple[str, str, str]], dry_run: bool) -> None:
"""
Check if destination filesystems have enough space. Prompt user if low.
"""
required_map = estimate_required_bytes_for_ops(ops)
for dev_id, info in required_map.items():
if dev_id in _confirmed_filesystems:
continue
req_bytes = info["bytes"]
count = info["count"]
sample_path = info["sample_path"]
if not sample_path:
continue
# Get free space
check_path = get_existing_parent(sample_path)
if not check_path:
continue
try:
usage = shutil.disk_usage(check_path)
free_bytes = usage.free
total_bytes = usage.total
except OSError:
continue
# Threshold: max(2 GiB, 5% of total) capped at 50 GiB for large drives
reserve_bytes = max(2 * 1024**3, min(int(total_bytes * 0.05), 50 * 1024**3))
estimated_free = free_bytes - req_bytes
is_low = (req_bytes > free_bytes) or (estimated_free < reserve_bytes)
if is_low:
header = "DRY RUN WARNING" if dry_run else "WARNING"
print(
f"\n{header}: Low disk space detected on destination device for '{sample_path}'"
)
print(f" Destination filesystem: {check_path}")
print(f" Current free space: {format_bytes(free_bytes)}")
print(f" Required ({count} files): {format_bytes(req_bytes)}")
if estimated_free < 0:
print(
f" Est. free after ops: {format_bytes(estimated_free)} (OVERFLOW by {format_bytes(-estimated_free)})"
)
else:
print(f" Est. free after ops: {format_bytes(estimated_free)}")
print(f" Reserve threshold: {format_bytes(reserve_bytes)}")
if not sys.stdin.isatty():
print(
"Refusing to proceed: destination space is low and no TTY is available to confirm."
)
sys.exit(1)
response = input(" Proceed anyway? [y/N] ").strip().lower()
if response not in ("y", "yes"):
print("Aborted by user.")
sys.exit(1)
_confirmed_filesystems.add(dev_id)
def is_cross_device(src_path, dest_path):
"""Check if source and destination are on different devices."""
try:
return os.stat(src_path).st_dev != os.stat(dest_path).st_dev
except OSError:
return True # Assume cross-device if we can't tell
def format_action_message(
operation_mode, filename, dest_filename, dest_dir, success, dry_run, used_prefix
):
"""Generate consistent action messages for all operations."""
if (
operation_mode == "rename"
or operation_mode == "lightroom"
or operation_mode == "lightroomimport"
):
if dry_run:
action = "Would rename"
else:
action = "Renamed" if success else "Failed to rename"
return f"{action} '{filename}' to '{dest_filename}'"
else: # copy or stackcopy
if operation_mode == "stackcopy" or used_prefix:
if dry_run:
action = "Would copy and rename"
else:
action = (
"Copied and renamed" if success else "Failed to copy and rename"
)
else:
if dry_run:
action = "Would copy"
else:
action = "Copied" if success else "Failed to copy"
return (
f"{action} '{filename}' to '{dest_filename}' in '{display_path(dest_dir)}'"
)
def main():
"""Main program entry point."""
# Set up argument parser
parser = argparse.ArgumentParser(
description="Process JPG files without corresponding raw files"
)
# Create a mutually exclusive group for the three operation modes
mode_group = parser.add_mutually_exclusive_group()
# Copy mode - requires source and destination
mode_group.add_argument(
"--copy",
nargs=2,
metavar=("SRC_DIR", "DEST_DIR"),
help="Copy JPG files without matching raw files from source to destination. Can be used with --prefix.",
)
# Rename mode - optional directory argument (renames files in-place)
mode_group.add_argument(
"--rename",
"-r",
nargs="?",
const=os.getcwd(),
metavar="DIR",
help="Rename JPG files without matching raw files in-place by adding ' stacked' (defaults to current directory)",
)
# Stack copy mode - optional directory argument (copies to 'stacked' subdirectory)
mode_group.add_argument(
"--stackcopy",
nargs="?",
const=os.getcwd(),
metavar="DIR",
help="Copy JPG files without matching raw files to a 'stacked' subdirectory with ' stacked' added to filenames",
)
# Lightroom mode - optional directory argument
mode_group.add_argument(
"--lightroom",
nargs="?",
const=os.getcwd(),
metavar="DIR",
help="Move input files (JPG and ORF) to a dated directory structure and rename the stacked JPG in place.",
)
# Lightroom import mode - optional directory argument
mode_group.add_argument(
"--lightroomimport",
nargs="?",
const=os.getcwd(),
metavar="DIR",
help=(
"Same as --lightroom, but moves remaining files to a dated directory structure "
f"under the user's Pictures directory (default: {os.path.join(_default_pictures_dir(), 'Lightroom')}/YEAR/DATE/). "
"The destination can be overridden via the STACKCOPY_LIGHTROOM_IMPORT_DIR environment variable."
),
)
# Add date filtering options
date_group = parser.add_argument_group(
"Date Filtering (optional, for copy operations)"
)
date_group.add_argument(
"--today",
action="store_true",
help="Process JPGs created today that don't have a corresponding raw file.",
)
date_group.add_argument(
"--yesterday",
action="store_true",
help="Process JPGs created yesterday that don't have a corresponding raw file.",
)
date_group.add_argument(
"--date",
metavar="YYYY-MM-DD",
help="Process JPGs from a specific date that don't have a corresponding raw file.",
)
# Add prefix option
parser.add_argument(
"--prefix",
metavar="PREFIX",
help="Add a custom prefix before ' stacked' in the filename when using --copy, --rename, or --stackcopy.",
)
# Add dry-run option
parser.add_argument(
"--dry",
"--dry-run",
dest="dry_run",
action="store_true",
help="Show what would happen without making any actual changes",
)
# Add verbose flag
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Show detailed information about processed files",
)
# Add overwrite protection option
parser.add_argument(
"--force",
action="store_true",
help="Overwrite existing files without prompting",
)
# Add debug flag for stack detection
parser.add_argument(
"--debug-stacks",
action="store_true",
help="Enable detailed diagnostic output for stack detection",
)
parser.add_argument(
"-i",
"--interactive",
action="store_true",
help="Show a summary and ask for confirmation before moving files (--lightroomimport only)",
)
parser.add_argument(
"-j",
"--jobs",
type=int,
default=1,
metavar="N",
help="Number of parallel copy workers to use for --copy/--stackcopy (default: 1)",
)
# Parse arguments
# --- 0. Execution Tracking & Summary Statistics ---
processed_count = 0
skipped_count = 0
failed_count = 0
moved_input_count = 0
moved_output_count = 0
stack_outputs_seen = 0
remaining_moved_count = 0
total_bytes_moved = 0
exec_start_time = None
exec_elapsed_time = 0
partial_failures_found = False
execution_results: dict[str, dict] = {}
args = parser.parse_args()
if args.jobs < 1:
parser.error("--jobs must be at least 1.")
# Clamp number of jobs to a reasonable limit
cpu_count = os.cpu_count() or 1
if args.jobs > cpu_count * 2:
if args.verbose:
print(
f"Warning: --jobs reduced from {args.jobs} to {cpu_count * 2} (2x CPU cores) to avoid resource exhaustion."
)
args.jobs = cpu_count * 2
if args.lightroom and not args.dry_run and args.jobs == 1:
# If user didn't explicitly request more jobs, pick something sensible
# 4 workers max, but don't exceed 2x CPU cores
auto_jobs = min(4, cpu_count * 2)
if args.verbose:
print(f"Auto-selecting {auto_jobs} worker jobs for Lightroom mode.")
args.jobs = auto_jobs
# lightroomimport always runs sequentially so files move in oldest-first order
if args.lightroomimport is not None:
args.jobs = 1
created_dirs = set()
# Determine the target date for filtering
target_date = None
if args.today:
target_date = date.today()
elif args.yesterday:
target_date = date.today() - timedelta(days=1)
elif args.date:
try:
target_date = datetime.strptime(args.date, "%Y-%m-%d").date()
except ValueError:
print(
f"Error: Date format for --date must be YYYY-MM-DD. You provided '{args.date}'."
)
sys.exit(1)
# If no operation mode is specified, show help and exit
if (
not args.copy
and args.rename is None
and args.stackcopy is None
and args.lightroom is None
and args.lightroomimport is None
):
parser.print_help()
sys.exit(1)
# Determine operation mode and set directories
if args.copy:
operation_mode = "copy"
src_dir = normalize_path(args.copy[0])
dest_dir = normalize_path(args.copy[1])
# Verify that the source directory exists
if not os.path.isdir(src_dir):
print(
f"Error: Source directory '{src_dir}' does not exist or is not a directory."
)
sys.exit(1)
# Check if source and destination are the same
if paths_are_same(src_dir, dest_dir):
print("Error: Source and destination directories cannot be the same.")
sys.exit(1)
# Ensure the destination directory exists, create if necessary (but not in dry run)
try:
ensure_directory_once(dest_dir, created_dirs, args.dry_run)
except OSError as e:
print(f"Error creating destination directory '{dest_dir}': {e}")
sys.exit(1)
elif args.rename is not None: # --rename mode
operation_mode = "rename"
work_dir = normalize_path(args.rename)
# Verify that the specified directory exists
if not os.path.isdir(work_dir):
print(
f"Error: Directory '{work_dir}' does not exist or is not a directory."
)
sys.exit(1)
# For rename mode, source and working directory are the same
src_dir = work_dir
dest_dir = work_dir # We're renaming in-place
elif (
args.lightroom is not None or args.lightroomimport is not None
): # --lightroom mode
operation_mode = (
"lightroom" if args.lightroom is not None else "lightroomimport"
)
work_dir = normalize_path(
args.lightroom if args.lightroom is not None else args.lightroomimport
)
# Verify that the specified directory exists
if not os.path.isdir(work_dir):
print(
f"Error: Directory '{work_dir}' does not exist or is not a directory."
)
sys.exit(1)
# For lightroom mode, source and working directory are the same
src_dir = work_dir
dest_dir = work_dir # We're renaming in-place
# Ensure the stack input directory exists
try:
ensure_directory_once(STACK_INPUT_DIR, created_dirs, args.dry_run)
except OSError as e:
print(f"Error creating stack input directory '{STACK_INPUT_DIR}': {e}")
sys.exit(1)
else: # --stackcopy mode
operation_mode = "stackcopy"
work_dir = normalize_path(args.stackcopy)
# Verify that the specified directory exists
if not os.path.isdir(work_dir):
print(
f"Error: Directory '{work_dir}' does not exist or is not a directory."
)
sys.exit(1)
# For stackcopy mode, source is the working directory
src_dir = work_dir
# Create a 'stacked' subdirectory for the copies
dest_dir = os.path.join(work_dir, "stacked")
try:
ensure_directory_once(dest_dir, created_dirs, args.dry_run)
except OSError as e:
print(f"Error creating stacked directory '{dest_dir}': {e}")
sys.exit(1)
# WSL performance warning — fires once if any involved path crosses the 9P bridge
wsl_check_paths = [src_dir, dest_dir]
if operation_mode in ("lightroom", "lightroomimport"):
wsl_check_paths.append(STACK_INPUT_DIR)
if operation_mode == "lightroomimport":
# For lightroomimport, also check the base import directory
_env_import_base = os.environ.get("STACKCOPY_LIGHTROOM_IMPORT_DIR")
if _env_import_base:
import_base = os.path.abspath(os.path.expanduser(_env_import_base))
else:
import_base = os.path.join(_default_pictures_dir(), "Lightroom")
wsl_check_paths.append(import_base)
_warn_wsl_performance(wsl_check_paths, operation_mode)
# Define a list of common raw photo extensions
RAW_EXTENSIONS = {
".orf",
".cr2",