#!/usr/bin/env python3 # coldcopy-sort: https://coldcopy.app/sort. Generated by tools/build-free-sort from codelawcorp/coldcopy # free-sort/free_sort.py and media-index/dates.py; do not edit by hand. """coldcopy-sort: the free tool of Coldcopy (https://coldcopy.app/sort). It sorts the photos and videos of ONE folder into /YYYY/YYYY-MM-DD/ by capture date. Max, 2026-11-01: a small safe piece of Coldcopy given away in a comment-for-DM reel («The only valid filetree sorting is by date»: no content categories). Usage: coldcopy-sort FOLDER [--into FOLDER] [--move] [--dry-run] Safety, as in the paid product: - it lists the plan first (day folders, file counts, sizes) and changes nothing until you type y; - it copies by default (each copy read back and compared byte for byte) and never deletes a file; --move renames instead of copying, only on the same drive (a rename moves no bytes and loses none); - a name already taken in a day folder gets a suffix (IMG_1-2.JPG), never an overwrite; the same bytes already there are skipped, so a second run copies only what is new. The day of a file (the same rule as `coldcopy sort`, dates.sort_day in dates.py, docs/jobs.md section 11): its capture date (EXIF DateTimeOriginal, QuickTime CreationDate, XMP/IPTC, CreateDate; a QuickTime date in UTC turned into this Mac's time zone), else the earlier of the file's creation and modification dates, marked "file date" in the plan. Files of one name in one folder (a Live Photo's HEIC and MOV, an AAE edit) share the day of the one with a capture date. Capture dates come from exiftool when it is installed, else from the tool's own reader of JPEG, HEIC and TIFF-based RAW (EXIF) and MOV/MP4 headers. This file runs from the repository (imports media-index/dates.py) or as the one-file bundle that tools/build-free-sort writes to landing/public/coldcopy-sort (dates.py embedded verbatim). It lives outside media-index/ on purpose: the bundle is one file and cannot import live.py, walk.py or journal.py, so it draws its own bar, walks and renames itself; the one-place rules of tests/test_one_place.py hold for the paid tool's modules (agent decision, 2026-11-15). Python 3.9 (macOS's /usr/bin/python3), standard library only. Tests: tests/test_free_sort.py (FS1-FS14).""" import sys as _sys, types as _types _DATES = r'''"""The capture date of a file and its day folder (docs/jobs.md sections 11 and 12): the one exiftool runner, the capture date in a file's tags, the times a file system keeps for it, the day folder path YYYY/MM/DD, and the day rules of the commands that file by date. It reads tags and file times only; it moves nothing and imports no module of media-index (the base of reorg_rules, device_days, sortfolder, device_plan and reorganize). The capture date (capture_date, local_day; Max, 2026-10-11): from capture metadata only, EXIF DateTimeOriginal → QuickTime CreationDate → XMP/IPTC DateCreated → EXIF CreateDate → QuickTime CreateDate / MediaCreateDate (UTC; a phone file name's local time within 14 h sets the day); an unset camera clock (1980-01-01, 1980-01-02, 1970-01-01) is no date. The day rules differ on purpose, each for the files its command meets; every one starts from capture_date and local_day: - coldcopy reorganize (reorg_rules.plan): a photo never takes its modification date; audio, video and documents without a capture date take it only when it is more than a day older than the file's arrival on the drive (reorg_rules.modified_date); any other file stays without a day, aside in /no-capture-date/. - the devices stage (card_day): a card file without a capture date takes its modification time (a camera or recorder sets it when it writes the file), else the import day. - coldcopy sort (sort_day): a file without a capture date takes the earliest plausible of its birth time and modification time (a copy keeps the older one), in the time zone of the nearest dated photo when one is given. Tests: media-index/test_dates.py (DT1-DT6), test_reorg_rules.py, test_device_days.py, test_sortfolder.py.""" import datetime, os, re, shutil, subprocess, time # epoch dates of cameras and phones whose clock was never set (FAT/DOS 1980-01-01, Unix 1970-01-01) UNSET_CLOCK = {datetime.date(1980, 1, 1), datetime.date(1980, 1, 2), datetime.date(1970, 1, 1)} VIDEO = {"MP4", "MOV", "M4V", "3GP", "AVI", "MTS", "M2TS", "M4A", "HEIC_MOV"} NAME_TS = re.compile(r"(20\d{2})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})") WITHIN = 14 * 3600 # s: a UTC date and a local time this close are one moment in two clocks def parse(v, today): if not isinstance(v, str) or len(v) < 10 or v.startswith("0000"): return None try: d = datetime.datetime.strptime(v[:19] if len(v) >= 19 else v[:10], "%Y:%m:%d %H:%M:%S" if len(v) >= 19 else "%Y:%m:%d") except ValueError: return None if d.date() in UNSET_CLOCK: return None # a camera whose clock was never set writes its epoch, not the capture day return d if 1980 <= d.year and d.date() <= today else None def capture_date(e, today): """(datetime, source) from capture metadata only; (None, None) when the file has none.""" video = str(e.get("FileType", "")).upper() in VIDEO for tag, src in [("DateTimeOriginal", "DateTimeOriginal"), ("CreationDate", "QuickTime CreationDate (local)"), ("DateCreated", "XMP/IPTC DateCreated"), ("CreateDate", "QuickTime CreateDate (UTC)" if video else "EXIF CreateDate"), ("MediaCreateDate", "QuickTime MediaCreateDate (UTC)")]: d = parse(e.get(tag), today) if d: return d, src return None, None def local_day(dt, src, stem): """QuickTime dates are UTC; a phone's file name holds its local time. Within 14 h, the name's day is the local day.""" m = NAME_TS.search(stem) if "UTC" not in src or not m: return dt, src try: named = datetime.datetime(*map(int, m.groups())) except ValueError: return dt, src if abs((named - dt).total_seconds()) <= 14 * 3600: return named, src + " → local time from the file name" return dt, src def file_times(path): """(modification time, birth time or None) of a file, in seconds. On the exFAT archive drive the birth time is when the file arrived there (archive-olia, 2026-10-16: 7,749 of its 9,325 files without a capture date arrived in 2026-07, their modification dates span 1995-2026).""" st = os.stat(path) return st.st_mtime, getattr(st, "st_birthtime", None) def day_dir(d): """The day folder of a date as a path, "YYYY/MM/DD": the capture-date tree of the archive drive (reorganize, sort) and the T7's pre-archive day folders (the devices stage, reorganize --tier staging) both start with it.""" return f"{d:%Y/%m/%d}" def card_day(entry, mtime, stem, today): """(date, where it comes from) of one card file, by the devices stage's rule (device_days.py's steps 2-4): its capture date (a QuickTime date in UTC moved to the device's local time when the file name or the file's modification time on the card is within 14 h of it: the camera writes both in its own clock), else the file's modification time on the card (a DJI Mic WAV has no capture tags), else TODAY, the import day (a clock that was never set, a date in the future).""" dt, src = capture_date(entry or {}, today) if dt: dt, src = local_day(dt, src, stem) if "UTC" in src and "file name" not in src and mtime is not None: local = datetime.datetime.fromtimestamp(mtime) if abs((local - dt).total_seconds()) <= WITHIN: return local.date(), src + " → local time from the file's modification time" return dt.date(), src if mtime is not None: d = datetime.datetime.fromtimestamp(mtime).date() if d not in UNSET_CLOCK and datetime.date(1980, 1, 1) <= d <= today: return d, "modification time" return today, "import day (no capture date, modification time unset or in the future)" def sort_day(entry, mtime, stem, today, birth=None, tz=None): """(date, where it comes from) of one file of the folder (Max, 2026-11-01, of an Instagram photo created 2021-10-16 and copied to the drive on 2026-10-31, filed under 2026/10/31: «IT IS NOT 2026!»; «reorganize rules are the smartest»): its capture date by reorganize's rule (capture_date: EXIF DateTimeOriginal → QuickTime CreationDate → XMP/IPTC DateCreated → CreateDate → MediaCreateDate, a phone's UTC date turned local by its name, an unset clock no date); without one, the earliest of its creation date (birth time) and modification time that is a plausible day (not an unset clock, not before 1980, not after TODAY): a copy keeps the older one, never the day of the copy; neither: TODAY. TZ: (timezone, name) of the nearest dated photo (sortfolder.tz_near): that day is the day there, else the Mac's.""" dt, src = capture_date(entry or {}, today) if dt: dt, src = local_day(dt, src, stem) return dt.date(), src seen = [] for t, what in ((birth, "creation date"), (mtime, "modification time")): if t is None: continue d = datetime.datetime.fromtimestamp(t, tz[0] if tz else None).date() if d not in UNSET_CLOCK and datetime.date(1980, 1, 1) <= d <= today: seen.append((d, what)) if seen: d, what = min(seen) return d, what + (" (the earlier of creation and modification)" if len(seen) > 1 else "") + ( f" in UTC{tz[0].tzname(None)[3:] or '+00:00'}, the time zone of {tz[1]} next to it" if tz else "") return today, "import day (no capture date; creation and modification date unset or in the future)" def find_exiftool(env): """The exiftool to run: the program the environment variable ENV names (a test's fake), else exiftool on the PATH; None when it is missing or cannot be run. Each caller says what a missing exiftool means for its command.""" exe = os.environ.get(env) or shutil.which("exiftool") return exe if exe and os.access(exe, os.X_OK) else None def run_exiftool(exe, files, args, tags, folder, names, jobs, progress, poll, list_errors="strict"): """Reading capture dates with exiftool: FILES (full paths) in JOBS contiguous batches at once (their sizes differ by one at most), each job `EXE ARGS... -@ TAGS...` with its own output file (a shared file interleaved the jobs' lines, 2026-10-11) and its own error file. NAMES: the file names of a job's list, output and errors in FOLDER, each a format of the job's number i ("b{i}", "o{i}.json", "e{i}.txt"). PROGRESS(done, last) is called every POLL seconds while the jobs run, with the number of files exiftool has read (its "======== " progress lines) and the last file's path. LIST_ERRORS: how a name that is no UTF-8 text is written into a list (the devices stage: "surrogateescape"). Ctrl+C (any exception): no exiftool is left running. -> [(output path, error path)], one per job.""" n = max(1, min(jobs, len(files))) procs = [] try: for i in range(n): batch = files[i * len(files) // n:(i + 1) * len(files) // n] # n contiguous batches, sizes differ by one at most arg, out, err = (os.path.join(folder, x.format(i=i)) for x in names) open(arg, "w", encoding="utf-8", errors=list_errors).write("".join(f + "\n" for f in batch)) o, e = open(out, "w"), open(err, "w") procs.append((subprocess.Popen([exe] + list(args) + ["-@", arg] + list(tags), stdout=o, stderr=e), o, e)) while True: done, last = 0, "" for _, _, e in procs: try: lines = [l for l in open(e.name, encoding="utf-8", errors="replace") if l.startswith("======== ")] except OSError: lines = [] done += len(lines) if lines: last = lines[-1][9:].rsplit(" [", 1)[0] progress(done, last) if all(p.poll() is not None for p, _, _ in procs): break time.sleep(poll) except BaseException: for p, _, _ in procs: # Ctrl+C: no exiftool left running if p.poll() is None: p.terminate() for p, _, _ in procs: try: p.wait(5) except subprocess.TimeoutExpired: p.kill() raise finally: for _, o, e in procs: o.close(); e.close() return [(o.name, e.name) for _, o, e in procs] ''' _m = _types.ModuleType("dates") exec(compile(_DATES, "dates.py", "exec"), _m.__dict__) _sys.modules["dates"] = _m import datetime, json, os, re, shutil, signal, struct, sys, tempfile, time sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "media-index")) import dates # the capture date and the day rule (docs/jobs.md sections 11 and 12) TOOL = "coldcopy-sort" STEPS = 4 PHOTO = {"jpg", "jpeg", "heic", "heif", "png", "gif", "tif", "tiff", "webp", "avif", "dng", "cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "raf", "orf", "rw2", "pef", "srw", "x3f", "3fr", "iiq", "aae"} VIDEO = {"mov", "mp4", "m4v", "3gp", "avi", "mts", "m2ts", "mkv", "insv", "lrv"} # exiftool's tags and options of the devices stage (device_days.TAGS, ARGS), copied: the bundle cannot import device_days TAGS = ["-SourceFile", "-FileType", "-EXIF:DateTimeOriginal", "-EXIF:CreateDate", "-XMP:DateCreated", "-XMP:DateTimeOriginal", "-XMP-photoshop:DateCreated", "-QuickTime:CreationDate", "-QuickTime:CreateDate", "-QuickTime:MediaCreateDate", "-IPTC:DateCreated"] ARGS = ["-json", "-fast", "-q", "-q", "-progress", "-charset", "filename=utf8", "-api", "LargeFileSupport=1"] CHUNK = 4 << 20 PARTIAL = ".coldcopy-sort-partial" # a test's slow copy: honoured only for a source inside the system temp folder (tests/test_free_sort.py FS10-FS11) SLOW = "COLDCOPY_SORT_TEST_DELAY" TTY = sys.stderr.isatty() COLOR = TTY and not os.environ.get("NO_COLOR") def c(code, s): return f"\033[{code}m{s}\033[0m" if COLOR else s def hms(s): s = max(0, int(s)) return f"{s // 3600}h{s // 60 % 60:02d}m{s % 60:02d}s" def size(n): for unit, k in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6), ("KB", 1e3)): if n >= k: return f"{n / k:.1f} {unit}" return f"{n} B" def title(text): if TTY: sys.stderr.write(f"\033]0;{TOOL} · {text}\007") sys.stderr.flush() def step(n, text): title(f"Step {n} of {STEPS} · {text}") print(c("1;36", f"==> Step {n} of {STEPS} · {text}"), file=sys.stderr, flush=True) class Bar: """One master bar per step: its action in capitals first, redrawn in place every 0.3 s on a terminal, kept at 100% in the scrollback when done; in a pipe one plain line at the end. A sub-line shows what holds it after 3 s without a move.""" def __init__(self, action, what, total=None, unit=""): self.action, self.what, self.total, self.unit = action, what, total, unit self.t0 = self.last_move = time.time() self.done_n, self.drawn, self.lines, self.sub = 0, 0.0, 0, "" def text(self, final=False): el = time.time() - self.t0 if self.total: f = min(1.0, self.done_n / self.total) if not final else 1.0 bar = "█" * int(f * 24) + "░" * (24 - int(f * 24)) fmt = size if self.unit == "bytes" else (lambda n: f"{n:,} {self.unit}") rem = "" if final else (f" · ~{hms(el / f * (1 - f))} remaining" if f > 0.01 and el > 0.5 else " · ~?h??m??s remaining") return (f"{c('1', self.action)} {self.what} {bar} {int(f * 100)}% · {fmt(self.total if final else self.done_n)} of " f"{fmt(self.total)} · {hms(el)} elapsed{rem}") return f"{c('1', self.action)} {self.what} · {self.done_n:,} {self.unit} · {hms(el)} elapsed" def update(self, n=None, sub=None, force=False): if n is not None and n != self.done_n: self.done_n, self.last_move, self.sub = n, time.time(), "" if sub is not None: self.sub = sub now = time.time() if not TTY or (not force and now - self.drawn < 0.3): return self.drawn = now out = [self.text()] if self.sub and now - self.last_move >= 3: out.append(f" └ {self.sub} · {hms(now - self.last_move)} so far") self._paint(out) def _paint(self, out): s = (f"\033[{self.lines - 1}A" if self.lines > 1 else "") + "\r" + "\n".join("\033[K" + l for l in out) extra = self.lines - len(out) if extra > 0: # the sub-line went: clear it, back to the bar's line s += "\n\033[K" * extra + f"\033[{extra}A" sys.stderr.write(s) sys.stderr.flush() self.lines = len(out) def end(self, note=""): line = self.text(final=True) + (f" · {note}" if note else "") if TTY: self._paint([line]); sys.stderr.write("\n") else: sys.stderr.write(line + "\n") sys.stderr.flush() def tick_forever(bar): """Keep the bar's clock moving while the main thread is in a long call (exiftool's output): a daemon thread redraws it.""" import threading stop = threading.Event() def run(): while not stop.wait(0.3): bar.update(force=True) threading.Thread(target=run, daemon=True).start() return stop # ---- the built-in reader of capture dates (used when exiftool is not installed) ------------------------------------------- def _tiff_dates(buf, off): """EXIF DateTimeOriginal and CreateDate of the TIFF structure that starts at OFF in BUF ({} when none).""" end = {b"II": "<", b"MM": ">"}.get(buf[off:off + 2]) if not end: return {} def u16(p): return struct.unpack(end + "H", buf[off + p:off + p + 2])[0] def u32(p): return struct.unpack(end + "I", buf[off + p:off + p + 4])[0] def ifd(p): n = u16(p) return [(u16(p + 2 + 12 * i), u32(p + 2 + 12 * i + 4), u32(p + 2 + 12 * i + 8)) for i in range(min(n, 512))] out = {} try: for tag, cnt, val in ifd(u32(4)): if tag == 0x8769: # the Exif sub-IFD for t, n, v in ifd(val): name = {0x9003: "DateTimeOriginal", 0x9004: "CreateDate"}.get(t) if name and n >= 19: out[name] = buf[off + v:off + v + 19].decode("ascii", "replace") except (struct.error, IndexError): pass return out def _exif_entry(path): with open(path, "rb") as f: buf = f.read(2 << 20) if buf[:4] in (b"II*\x00", b"MM\x00*"): # TIFF-based RAW (DNG, CR2, NEF, ARW, …) return _tiff_dates(buf, 0) i = buf.find(b"Exif\x00\x00") # JPEG's APP1, HEIC's Exif item while i >= 0: got = _tiff_dates(buf, i + 6) if got: return got i = buf.find(b"Exif\x00\x00", i + 1) return {} def _boxes(f, start, stop): """(type, data start, end) of the QuickTime/MP4 boxes between START and STOP of open file F.""" p = start while p + 8 <= stop: f.seek(p) head = f.read(16) if len(head) < 8: return n, kind = struct.unpack(">I4s", head[:8]) hl = 8 if n == 1 and len(head) >= 16: n, hl = struct.unpack(">Q", head[8:16])[0], 16 elif n == 0: n = stop - p if n < hl: return yield kind, p + hl, p + n p += n QT_LOCAL = re.compile(rb"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})([+-]\d{2}):?(\d{2})") def _quicktime_entry(path): out = {} with open(path, "rb") as f: stop = os.fstat(f.fileno()).st_size for kind, a, b in _boxes(f, 0, stop): if kind != b"moov" or b - a > 256 << 20: continue f.seek(a) moov = f.read(b - a) i = moov.find(b"mvhd") if i >= 4: v = moov[i + 4] secs = struct.unpack(">Q", moov[i + 8:i + 16])[0] if v == 1 else struct.unpack(">I", moov[i + 8:i + 12])[0] if secs: t = datetime.datetime(1904, 1, 1) + datetime.timedelta(seconds=secs) out["CreateDate"] = t.strftime("%Y:%m:%d %H:%M:%S") k = moov.find(b"com.apple.quicktime.creationdate") m = QT_LOCAL.search(moov, k if k >= 0 else len(moov)) if m: y, mo, d, h, mi, s, oh, om = (x.decode() for x in m.groups()) out["CreationDate"] = f"{y}:{mo}:{d} {h}:{mi}:{s}{oh}:{om}" break return out def own_entry(path): """An exiftool-shaped entry ({"FileType", "DateTimeOriginal", "CreateDate", "CreationDate"}) from the file's headers.""" ext = path.rsplit(".", 1)[-1].upper() if "." in os.path.basename(path) else "" e = {"FileType": ext} try: e.update(_quicktime_entry(path) if ext.lower() in VIDEO else _exif_entry(path)) except OSError: pass return e # ---- the plan ---------------------------------------------------------------------------------------------------------- def is_media(name): return not name.startswith(".") and "." in name and name.rsplit(".", 1)[-1].lower() in PHOTO | VIDEO def list_folder(src, skip): """[relative path] of every photo and video under SRC (hidden files and folders, and SKIP, left out), with a ticker; and the count of other files left where they are.""" bar = Bar("LISTING", f"{src}/", unit="files found") found, other = [], 0 for d, dirs, names in os.walk(src): dirs[:] = sorted(x for x in dirs if not x.startswith(".") and os.path.join(d, x) not in skip) for n in sorted(names): if is_media(n): found.append(os.path.relpath(os.path.join(d, n), src)) elif not n.startswith("."): other += 1 bar.update(len(found)) bar.done_n = len(found) bar.end(f"{other:,} other files stay where they are" if other else "") return found, other def read_dates(src, files): """{relative path: exiftool-shaped entry}, from exiftool when installed (dates.run_exiftool), else the own reader.""" exe = dates.find_exiftool("COLDCOPY_SORT_EXIFTOOL") full = [os.path.join(src, f) for f in files] out = {} if exe and files: bar = Bar("READING", "capture dates (exiftool)", len(files), "files") work = tempfile.mkdtemp(prefix="coldcopy-sort.") stop = tick_forever(bar) try: jobs = dates.run_exiftool(exe, full, ARGS, TAGS, work, ("b{i}", "o{i}.json", "e{i}.txt"), 4, lambda n, last: bar.update(min(n, len(files)), sub=f"READING {last}"), 0.2) for o, _ in jobs: try: for x in json.load(open(o)) if os.path.getsize(o) else []: out[os.path.relpath(x.get("SourceFile", ""), src)] = x except ValueError: pass finally: stop.set() shutil.rmtree(work, ignore_errors=True) bar.end() return out, "exiftool" bar = Bar("READING", "capture dates (headers of JPEG, HEIC, RAW, MOV, MP4)", len(files), "files") for i, (f, p) in enumerate(zip(files, full)): bar.update(i, sub=f"READING {f}") out[f] = own_entry(p) bar.done_n = len(files) bar.end() return out, "built-in reader (brew install exiftool reads more formats)" def day_of(entry, path, today): """(date, source, by_capture): dates.capture_date and dates.local_day, a UTC QuickTime date turned into this Mac's time zone; without a capture date, dates.sort_day's file-date rule (the earlier of creation and modification).""" stem = os.path.splitext(os.path.basename(path))[0] dt, src = dates.capture_date(entry or {}, today) if dt: dt, src = dates.local_day(dt, src, stem) if "UTC" in src and "file name" not in src: dt = dt.replace(tzinfo=datetime.timezone.utc).astimezone().replace(tzinfo=None) src += " → this Mac's time zone" if dt.date() <= today: return dt.date(), src, True mtime, birth = dates.file_times(path) d, src = dates.sort_day({}, mtime, stem, today, birth=birth) return d, "file date: " + src, False def plan(src, files, entries, into, today): """[(relative source, target path, date, source of the date, by capture)] with the day folders and suffixes settled.""" days = {f: day_of(entries.get(f), os.path.join(src, f), today) for f in files} stems = {} for f, (d, s, cap) in days.items(): # a Live Photo's HEIC, MOV and AAE share one day if cap: stems.setdefault(os.path.splitext(f)[0].lower(), (d, s)) for f, (d, s, cap) in list(days.items()): k = os.path.splitext(f)[0].lower() if not cap and k in stems: days[f] = (stems[k][0], "the capture date of " + stems[k][1].split(" →")[0] + " of the same name", True) taken, rows = set(), [] for f in sorted(files, key=lambda x: (days[x][0], x)): d, s, cap = days[f] folder = os.path.join(into, f"{d:%Y}", f"{d:%Y-%m-%d}") name = os.path.basename(f) base, ext = os.path.splitext(name) target, k = os.path.join(folder, name), 1 while target.lower() in taken or (os.path.lexists(target) and not same(os.path.join(src, f), target)): k += 1 target = os.path.join(folder, f"{base}-{k}{ext}") taken.add(target.lower()) rows.append((f, target, d, s, cap)) return rows def same(a, b): """True when files A and B hold the same bytes (size first, then the bytes).""" try: if os.path.getsize(a) != os.path.getsize(b): return False with open(a, "rb") as x, open(b, "rb") as y: while True: p, q = x.read(CHUNK), y.read(CHUNK) if p != q: return False if not p: return True except OSError: return False def show_plan(src, into, rows, other, reader, move): print(f"\n── Plan: {'move' if move else 'copy'} {len(rows):,} files from {src}/ into {into}/ ──") print(f"{into}/") per = {} for f, t, d, s, cap in rows: n, b, fb, clash, there = per.get(os.path.dirname(t), (0, 0, 0, 0, 0)) exists = os.path.lexists(t) per[os.path.dirname(t)] = (n + 1, b + os.path.getsize(os.path.join(src, f)), fb + (not cap), clash + (os.path.basename(t) != os.path.basename(f)), there + exists) for folder in sorted(per): n, b, fb, clash, there = per[folder] notes = [x for x in (f"{fb:,} by file date" if fb else "", f"{clash:,} renamed: name taken" if clash else "", f"{there:,} already there, skipped" if there else "") if x] print(f" {os.path.relpath(folder, into)}/ {n:,} files {size(b)}" + (c("33", " · " + " · ".join(notes)) if notes else "")) total = sum(os.path.getsize(os.path.join(src, f)) for f, *_ in rows) fb = sum(1 for r in rows if not r[4]) clash = sum(1 for f, t, *_ in rows if os.path.basename(t) != os.path.basename(f)) print(f"\n Files: {len(rows):,} ({size(total)}) in {len(per):,} day folders") print(f" Capture dates read by: {reader}") if fb: print(c("33", f" By file date (no capture date in the file): {fb:,}")) for f, t, d, s, cap in rows: if not cap: print(c("33", f" {f} → {os.path.relpath(t, into)} ({s})")) if clash: print(f" Renamed because the name is taken in its day folder: {clash:,}") for f, t, *_ in rows: if os.path.basename(t) != os.path.basename(f): print(f" {f} → {os.path.relpath(t, into)}") if other: print(f" Not photos or videos, left where they are: {other:,}") print((" Files are moved by a rename on this drive; nothing is deleted." if move else f" Files are copied and read back byte for byte; {src}/ is not changed and nothing is deleted.")) sys.stdout.flush() # the plan before the next step line, also in a pipe def ask(question): """y or n, read from the terminal (also when the script came through a pipe); keys typed before the question are dropped. No terminal: n.""" if sys.stdin.isatty(): rd, wr = sys.stdin, sys.stderr else: try: # curl … | python3 -: stdin is the script, the answer comes from the terminal rd = wr = open("/dev/tty", "r+") except OSError: print(f"{question} no terminal to answer in: nothing changed", file=sys.stderr) return False try: import termios termios.tcflush(rd.fileno(), termios.TCIFLUSH) except Exception: pass title("waiting for your answer") wr.write(c("1", f"{question} [y/N] ")) wr.flush() a = rd.readline().strip().lower() if rd is not sys.stdin: rd.close() return a in ("y", "yes") class Copier: def __init__(self, src, rows, move, log): self.src, self.rows, self.move, self.log = src, rows, move, log self.done, self.skipped, self.partial = [], [], None self.delay = float(os.environ.get(SLOW, "0") or 0) if os.path.realpath(src).startswith( os.path.realpath(tempfile.gettempdir())) else 0.0 def run(self): total = sum(os.path.getsize(os.path.join(self.src, f)) for f, *_ in self.rows) bar = Bar("MOVING" if self.move else "COPYING", "files into their day folders", total, "bytes") moved = 0 with open(self.log, "a", encoding="utf-8") as log: for f, t, d, s, cap in self.rows: a = os.path.join(self.src, f) n = os.path.getsize(a) if os.path.lexists(t) and same(a, t): self.skipped.append(f) moved += n bar.update(moved) continue os.makedirs(os.path.dirname(t), exist_ok=True) if self.move: os.rename(a, t) else: self.copy(a, t, bar, moved) log.write(f"{'moved' if self.move else 'copied'}\t{a}\t{t}\t{d}\t{s}\n") log.flush() self.done.append(f) moved += n bar.update(moved) bar.end(f"{len(self.done):,} {'moved' if self.move else 'copied'}" + (f", {len(self.skipped):,} already there" if self.skipped else "")) def copy(self, a, t, bar, before): """A copy under a temporary name, read back and compared, then renamed to T: a stop never leaves half a file under a real name.""" tmp = os.path.join(os.path.dirname(t), PARTIAL + "-" + os.path.basename(t)) self.partial = tmp with open(a, "rb") as x, open(tmp, "wb") as y: got = 0 while True: b = x.read(CHUNK) if not b: break y.write(b) got += len(b) bar.update(before + got, sub=f"COPYING {os.path.basename(a)}") if self.delay: time.sleep(self.delay) y.flush() os.fsync(y.fileno()) shutil.copystat(a, tmp) if not same(a, tmp): os.unlink(tmp) raise OSError(f"the copy of {a} differs from it after the read back: removed, nothing else changed") os.rename(tmp, t) self.partial = None def main(argv): import argparse p = argparse.ArgumentParser(prog=TOOL, description="Sort the photos and videos of one folder into YYYY/YYYY-MM-DD/ " "folders by capture date. Shows the plan and changes nothing until you type y. " "https://coldcopy.app/sort") p.add_argument("folder", help="the folder to sort (its subfolders too)") p.add_argument("--into", help='where the day folders go (default: " sorted" next to it)') p.add_argument("--move", action="store_true", help="rename the files into the day folders instead of copying them " "(same drive only; nothing is deleted)") p.add_argument("--dry-run", action="store_true", help="show the plan only") a = p.parse_args(argv) src = os.path.abspath(os.path.expanduser(a.folder)).rstrip("/") or "/" if not os.path.isdir(src): print(c("31", f"{TOOL}: {src} is not a folder"), file=sys.stderr) return 2 into = os.path.abspath(os.path.expanduser(a.into)) if a.into else src + " sorted" probe = into while not os.path.exists(probe): probe = os.path.dirname(probe) if a.move and os.stat(probe).st_dev != os.stat(src).st_dev: print(c("31", f"{TOOL}: --move works only on one drive: {into} is on another drive than {src}; copy instead"), file=sys.stderr) return 2 today = datetime.date.today() state = {"step": 1, "what": "listing", "copier": None} def on_term(*_): raise KeyboardInterrupt signal.signal(signal.SIGTERM, on_term) signal.signal(signal.SIGHUP, on_term) try: step(1, f"LISTING photos and videos in {src}/") files, other = list_folder(src, {into}) if not files: print(f"Skipping the rest: no photos or videos in {src}/", file=sys.stderr) title("done") return 0 state.update(step=2, what="reading capture dates") step(2, f"READING the capture dates of {len(files):,} files") entries, reader = read_dates(src, files) state.update(step=3, what="the plan") step(3, "PLANNING the day folders") rows = plan(src, files, entries, into, today) show_plan(src, into, rows, other, reader, a.move) state.update(step=4, what="copying") if a.dry_run: step(4, "COPYING: skipped") print("Skipping the copy: --dry-run. Nothing changed.", file=sys.stderr) title("done") return 0 if not ask(f"\n{'Move' if a.move else 'Copy'} {len(rows):,} files into {into}/?"): print("Nothing changed: you did not type y.", file=sys.stderr) title("stopped") return 0 step(4, f"{'MOVING' if a.move else 'COPYING'} {len(rows):,} files into {into}/") os.makedirs(into, exist_ok=True) log = os.path.join(into, f"coldcopy-sort {datetime.datetime.now():%Y-%m-%d %H%M%S}.tsv") state["copier"] = cp = Copier(src, rows, a.move, log) cp.run() print(c("32", f"Done: {len(cp.done):,} files {'moved' if a.move else 'copied'} into {into}/") + (f", {len(cp.skipped):,} were there already" if cp.skipped else "") + f". The list: {log}") print(f"\nThe full Coldcopy keeps a second copy in S3 Glacier Deep Archive in your own AWS account and catches " f"duplicates by content: https://coldcopy.app/") title("done") return 0 except KeyboardInterrupt: cp = state["copier"] if cp and cp.partial and os.path.exists(cp.partial): os.unlink(cp.partial) sys.stderr.write("\n") print(c("31", f"STOPPED in step {state['step']} of {STEPS} ({state['what']})"), file=sys.stderr) if cp: left = len(cp.rows) - len(cp.done) - len(cp.skipped) print(f" {'Moved' if cp.move else 'Copied'}: {len(cp.done):,} files, listed in {cp.log}", file=sys.stderr) print(f" Partly copied: none (the file in flight was removed)\n Not done: {left:,} files", file=sys.stderr) print(" Nothing was deleted. The next run skips the files already in place and does the rest.", file=sys.stderr) else: print(" Nothing changed.", file=sys.stderr) title("stopped") return 130 except OSError as e: print(c("31", f"{TOOL}: {e}"), file=sys.stderr) title("stopped") return 1 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))