dirrift 0.2.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.
dirrift/app.py ADDED
@@ -0,0 +1,1452 @@
1
+ # Copyright (c) 2026 Charly Rousseau <charly.rousseau@icm-institute.org>
2
+ # Paris Brain Institute (Institut du Cerveau) — Laboratory of structural plasticity
3
+ # https://parisbraininstitute.org/paris-brain-institute-research-teams/plastic-laboratory-brain-plasticity
4
+ # SPDX-License-Identifier: GPL-3.0-or-later
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ import shlex
9
+ import subprocess
10
+ import threading
11
+ import time
12
+ import traceback
13
+ from collections import Counter
14
+ from concurrent.futures import ThreadPoolExecutor
15
+ from functools import partial
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING
18
+
19
+ from rich.text import Text
20
+ from textual import work
21
+ from textual.app import App, ComposeResult
22
+ from textual.binding import Binding
23
+ from textual.containers import Vertical
24
+ from textual.widgets import Header, Static, DataTable, Footer
25
+
26
+ from dirrift.model import (FileEntry, DirNode, ViewMode, SORT_KEYS, FileStatus, STATUS_ORDER,
27
+ STATUS_STYLE, STATUS_ICON, COL_KEYS, BatchTask, Side, FileKind, SUMMARY_GLYPHS,
28
+ MutationRequirement)
29
+ from dirrift.file_ops import FileOps
30
+ from dirrift.summary import delete_breakdown, overwrite_warning, selection_notes, similarity_bar, subset_relation
31
+ from dirrift.file_diffs import is_text_file, _TUI_PROGS, _GUI_PROGS, builtin_diff
32
+ from dirrift.screens import (ScanOverlay, LoadingScreen, InputModal, HelpScreen, ConfirmScreen,
33
+ DiffToolScreen, DiffOutputScreen)
34
+ from dirrift.styling import set_theme, styled, Sty, sty, as_plain, fmt
35
+ from dirrift.utils import dbg, fmt_size, fmt_mtime, tagged_name, log_info, log_warning, log_error
36
+ from dirrift.exceptions import DirriftError, AliasError
37
+
38
+ if TYPE_CHECKING:
39
+ from dirrift.session import ComparisonSession
40
+ from dirrift.hashing import HashCache
41
+
42
+
43
+ HELP_BROWSING = '''\
44
+ [b]Navigation[/b]
45
+ ↑ / k move up
46
+ ↓ / j move down
47
+ g / G jump to top / bottom
48
+
49
+ [b]Selection[/b]
50
+ space toggle mark (dir: all children)
51
+ Shift+↓ / J mark + move down (ranger)
52
+ Shift+↑ / K mark + move up (ranger)
53
+ u unmark all
54
+
55
+ [b]Search & Filter[/b]
56
+ / search — jump to match (vim/less)
57
+ n / N next / previous match
58
+ f filter — hide non-matching rows (htop)
59
+
60
+ [b]Display[/b]
61
+ i toggle hide/show same files
62
+ t toggle tree / list view
63
+ s cycle sort column
64
+ S reverse sort direction
65
+ '''
66
+
67
+ HELP_ACTIONS = '''\
68
+ [b]Actions[/b] (marked rows, else current row)
69
+ [dim] in tree mode a directory means all children[/dim]
70
+ d delete from LEFT
71
+ D delete from RIGHT
72
+ c copy to the side where it is missing
73
+ < keep RIGHT, overwrite left
74
+ > keep LEFT, overwrite right
75
+ b keep both — .LEFT / .RIGHT, cross-copy
76
+ o open in diff tool (text files only)
77
+
78
+ [b]Tree mode[/b]
79
+ ← / → collapse (or parent) / expand
80
+ E / C expand all / collapse all
81
+
82
+ [b]Other[/b]
83
+ r re-scan both directories
84
+ ? this help
85
+ q quit
86
+
87
+ [dim]Every action confirms first, re-checks size and mtime,
88
+ and skips anything that changed.[/dim]
89
+ '''
90
+
91
+ HELP_PAGES = (HELP_BROWSING, HELP_ACTIONS)
92
+
93
+ STALE = '\x00stale:' # Sentinel prefix for stale rows
94
+ ABORTED = '\x00aborted' # Sentinel for tasks never attempted because the batch was stopped
95
+ _ACTIONABLE_KINDS = frozenset({FileKind.REGULAR, FileKind.SYMLINK})
96
+
97
+
98
+ class FileTable(DataTable):
99
+ """The file table. In tree mode, ← / → fold and unfold directories.
100
+
101
+ DataTable binds ← / → itself (horizontal scrolling), and the focused widget's
102
+ bindings win over the app's: bound on the app, the two keys never arrived.
103
+ """
104
+ BINDINGS = [
105
+ Binding('left', 'app.collapse_node', 'Collapse', show=False),
106
+ Binding('right', 'app.expand_node', 'Expand', show=False),
107
+ ]
108
+
109
+
110
+ class DirRift(App):
111
+ """Textual app for parallel folder comparison with optional deletion.
112
+
113
+ All disk mutations are delegated to ``FileOps``.
114
+ """
115
+ TITLE = 'DirRift'
116
+ SUB_TITLE = 'parallel binary diff'
117
+
118
+ CSS = '''
119
+ Screen { layers: base overlay; }
120
+ #info_bar { height: 2; background: $primary-darken-3; padding: 0 1; }
121
+ #info_bar_paths { height: 1; content-align: left middle; }
122
+ #info_bar_meta { height: 1; content-align: left middle; background: $primary-darken-2; }
123
+ #summary_bar { height: 1; background: $primary-darken-1; padding: 0 1; content-align: left middle; }
124
+ DataTable { height: 1fr; }
125
+ '''
126
+
127
+ BINDINGS = [
128
+ Binding('d', 'del_left', 'Del Left'),
129
+ Binding('D', 'del_right', 'Del Right'),
130
+ Binding('c', 'copy_missing', 'Copy→Missing'),
131
+ Binding('less_than_sign', 'resolve_right', '←Overwrite'),
132
+ Binding('greater_than_sign', 'resolve_left', '→Overwrite'),
133
+ Binding('b', 'keep_both', 'Keep Both'),
134
+ Binding('o', 'open_diff', 'Diff'),
135
+ Binding('i', 'toggle_same', 'Show/Hide ≡'),
136
+ Binding('slash', 'search', 'Search'),
137
+ Binding('f', 'filter', 'Filter'),
138
+ Binding('n', 'search_next', 'Next match'),
139
+ Binding('N', 'search_prev', 'Prev match'),
140
+ Binding('s', 'sort_next', 'Sort'),
141
+ Binding('r', 'rescan', 'Rescan'),
142
+ Binding('j', 'cursor_down', '↓', show=False),
143
+ Binding('k', 'cursor_up', '↑', show=False),
144
+ Binding('g', 'goto_top', 'Top', show=False),
145
+ Binding('G', 'goto_bottom', 'Bot', show=False),
146
+ Binding('J', 'mark_down', 'Mark↓', show=False),
147
+ Binding('K', 'mark_up', 'Mark↑', show=False),
148
+ Binding('shift+down', 'mark_down', 'Mark↓', show=False),
149
+ Binding('shift+up', 'mark_up', 'Mark↑', show=False),
150
+ Binding('S', 'sort_reverse', 'Sort Rev', show=False),
151
+ Binding('space', 'toggle_mark', 'Mark', show=False),
152
+ Binding('u', 'unmark_all', 'Unmark', show=False),
153
+ Binding('t', 'toggle_view', 'Tree/list'),
154
+ Binding('E', 'expand_all', 'Expand all', show=False),
155
+ Binding('C', 'collapse_all', 'Collapse all', show=False),
156
+ Binding('question_mark', 'help', '?'),
157
+ Binding('q', 'quit', 'Quit'),
158
+ ]
159
+
160
+ # ── init ──────────────────────────────────────────────────────────────
161
+ def __init__(self, session: ComparisonSession, file_ops: FileOps) -> None:
162
+ super().__init__()
163
+
164
+ # ── collaborators ────────────────────────────────────────────────
165
+ # The session owns configuration, scanners, cache and algorithm.
166
+ # This class owns only what the user changes by pressing keys.
167
+ self._session = session
168
+ self._cfg = session.cfg
169
+ self._file_ops = file_ops
170
+
171
+ # ── run control (main thread only) ───────────────────────────────
172
+ self._busy = False # a scan or batch is in flight
173
+ self._scan_done = False # a comparison has completed → exit code is meaningful
174
+ self._quit_warned = False # q pressed once during a batch; the next q abandons it
175
+ self._cancel = threading.Event()
176
+ self._cancel_lock = threading.Lock()
177
+
178
+ # ── view state ───────────────────────────────────────────────────
179
+ self._all: list[FileEntry] = []
180
+ self._visible: list[DirNode | FileEntry] = []
181
+ self._view_mode = ViewMode.LIST
182
+ self._collapsed: set[str] = set()
183
+ self._marked: set[str] = set() # rel_paths of marked rows
184
+ self._sort_col = 0 # index into SORT_KEYS
185
+ self._sort_rev = False
186
+ self._filter_pattern = ''
187
+ self._search_pattern = ''
188
+ # Seeded from config, then owned here: 'i' toggles it.
189
+ self._show_same = self._cfg.show_identical
190
+
191
+ # ── sticky notices (survive summary-bar churn) ───────────────────
192
+ self._cache_note: str | None = None
193
+
194
+ log_info(f'init: L={self._cfg.left} R={self._cfg.right} '
195
+ f'algo={self._session.algo} workers={self._cfg.workers} '
196
+ f'dry_run={self._file_ops.dry_run} cache={self._cfg.cache}')
197
+
198
+ @property
199
+ def left_dir(self) -> Path:
200
+ return self._cfg.left
201
+
202
+ @property
203
+ def right_dir(self) -> Path:
204
+ return self._cfg.right
205
+
206
+ @property
207
+ def _algo(self) -> str:
208
+ """The algorithm actually in use — may have been adopted from the cache."""
209
+ return self._session.algo
210
+
211
+ @property
212
+ def _deref(self) -> bool:
213
+ return self._cfg.dereference
214
+
215
+ @property
216
+ def _prune_empty(self) -> bool:
217
+ return self._cfg.prune_empty_dirs and not self._file_ops.dry_run
218
+
219
+ @property
220
+ def _tag_left(self) -> str:
221
+ return self._cfg.tag_left
222
+
223
+ @property
224
+ def _tag_right(self) -> str:
225
+ return self._cfg.tag_right
226
+
227
+ @property
228
+ def _n_workers(self) -> int:
229
+ return self._cfg.workers
230
+
231
+ def _claim(self, what: str) -> bool:
232
+ """Take the single work slot, or explain why not.
233
+
234
+ .. note::
235
+ Main thread only.
236
+ """
237
+ if self._busy:
238
+ self._set_summary(styled(f'busy — {what} refused', Sty.WARN))
239
+ return False
240
+ self._busy = True
241
+ return True
242
+
243
+ @staticmethod
244
+ def _sum_sizes(sizes) -> int:
245
+ """Total bytes, ignoring missing sides and the UNKNOWN_SIZE sentinel."""
246
+ return sum(s for s in sizes if s is not None and s > 0)
247
+
248
+ # ── layout ────────────────────────────────────────────────────────────
249
+ def compose(self) -> ComposeResult:
250
+ yield Header()
251
+ with Vertical(id='info_bar'):
252
+ yield Static('', id='info_bar_paths')
253
+ yield Static('', id='info_bar_meta')
254
+ yield ScanOverlay(id='scan_overlay')
255
+ yield FileTable(id='table', cursor_type='row', zebra_stripes=True)
256
+ yield Static('Initialising…', id='summary_bar')
257
+ yield Footer()
258
+
259
+ # ── theme ─────────────────────────────────────────────────────────────
260
+ def watch_dark(self, dark: bool) -> None: # FIXME: check textual version and amend
261
+ """React to Textual dark/light toggle."""
262
+ set_theme('dark' if dark else 'light')
263
+ if self._all:
264
+ self._rebuild_table()
265
+ self._show_summary()
266
+
267
+ def _info_bar_paths(self) -> str:
268
+ return (f'{styled("L:", Sty.ACCENT)} {as_plain(self.left_dir)} '
269
+ f'{styled("R:", Sty.ACCENT)} {as_plain(self.right_dir)}')
270
+
271
+ def _info_bar_meta(self) -> str:
272
+ parts = [styled(f'Hash algo: {self._algo} {self._n_workers} threads', Sty.MUTED)]
273
+ if self._file_ops.dry_run:
274
+ parts.append(styled('DRY-RUN', Sty.ERR))
275
+ if self._cfg.same_fs:
276
+ parts.append(styled('SAME-FS', Sty.INFO))
277
+ excluded = self._session.excl_left or self._session.excl_right
278
+ if excluded:
279
+ parts.append(fmt('OVERLAP (excluding {}/)', excluded.name, role=Sty.WARN))
280
+ if self._cache_note:
281
+ parts.append(styled('CACHE REJECTED', Sty.ERR))
282
+ elif self._cache is not None:
283
+ parts.append(styled(f'CACHE ({len(self._cache):,})', Sty.OK))
284
+ if self._filter_pattern:
285
+ parts.append(fmt('/{}/', self._filter_pattern, role=Sty.WARN))
286
+ sort_name = SORT_KEYS[self._sort_col][1]
287
+ sort_arrow = '▼' if self._sort_rev else '▲'
288
+ parts.append(styled(f'sort: {sort_name} {sort_arrow}', Sty.MUTED))
289
+ if self._cache is not None and self._cache.n_bad_rows:
290
+ parts.append(styled(f'{self._cache.n_bad_rows:,} bad cache rows', Sty.WARN))
291
+ if self._marked:
292
+ parts.append(styled(f'{len(self._marked)} marked', Sty.ACCENT))
293
+ return ' '.join(parts)
294
+
295
+ def _refresh_info_bar(self) -> None:
296
+ self.query_one('#info_bar_paths', Static).update(self._info_bar_paths())
297
+ self.query_one('#info_bar_meta', Static).update(self._info_bar_meta())
298
+
299
+ def _show_scan_overlay(self, msg: str = '⏳ Scanning…') -> None:
300
+ overlay = self.query_one('#scan_overlay', ScanOverlay)
301
+ overlay.set_phase(msg)
302
+ overlay.styles.display = 'block'
303
+
304
+ def _hide_scan_overlay(self) -> None:
305
+ self.query_one('#scan_overlay', ScanOverlay).styles.display = 'none'
306
+
307
+ def on_mount(self) -> None:
308
+ self._refresh_info_bar()
309
+ self._setup_columns()
310
+ if self._claim('initial scan'):
311
+ self._busy = True
312
+ self._start_scan()
313
+
314
+ @property
315
+ def _cache(self) -> HashCache | None:
316
+ """The session's cache, or None if absent or rejected. Read-only —
317
+ rejection goes through ``_cache_unusable`` so it cannot be silently reset."""
318
+ return self._session.cache
319
+
320
+ def _cache_stats(self, rich: bool = True) -> str:
321
+ """Formatted cache hit/miss stats. Used in progress, summary, and debug."""
322
+ if not self._cache:
323
+ return ''
324
+ h, m = self._cache.hits, self._cache.misses
325
+ total = h + m
326
+ if total == 0:
327
+ return 'cache: no lookups'
328
+ pairs = total // 2
329
+ cached = h // 2
330
+ pct = int(h / total * 100)
331
+ if rich:
332
+ return f'cache {styled(f"✓{cached}", Sty.OK)}/{pairs} pairs ({pct}%)'
333
+ return f'cache ✓{cached}/{pairs} pairs ({pct}%)'
334
+
335
+ def _cache_unusable(self, msg: str) -> None:
336
+ """Drop the cache and stop retrying. Main thread."""
337
+ self._session.drop_cache(msg) # also blocks reload on rescan
338
+ self._cache_note = msg
339
+ self._refresh_info_bar()
340
+ self._set_summary(fmt('⚠ {}', msg, role=Sty.ERR))
341
+ self.push_screen(ConfirmScreen('Cache not used — continuing without it',
342
+ detail=msg, action='Continue', show_cancel=False))
343
+
344
+ # ── background scan ───────────────────────────────────────────────────
345
+
346
+ def _on_scan_failed(self, exc: BaseException) -> None:
347
+ """A root became unreadable between runs — usually an unmount."""
348
+ self._busy = False
349
+ self._hide_scan_overlay()
350
+ self._set_summary(fmt('⚠ scan failed: {}', exc, role=Sty.ERR))
351
+
352
+ def _scan_notes(self, rich: bool = True) -> str:
353
+ """Per-side counters from the two DirScanner objects."""
354
+ left, right = self._session.left_scanner, self._session.right_scanner
355
+ excl = left.n_excluded + right.n_excluded
356
+ skip = left.n_skipped + right.n_skipped
357
+ errs = left.n_errors + right.n_errors
358
+ parts = []
359
+ if excl:
360
+ parts.append(styled(f'{excl:,} excluded', Sty.MUTED) if rich else f'{excl} excluded')
361
+ if skip:
362
+ parts.append(styled(f'{skip:,} not traversed', Sty.WARN) if rich else f'{skip} skipped')
363
+ if errs:
364
+ parts.append(styled(f'{errs:,} unreadable', Sty.ERR) if rich else f'{errs} errors')
365
+ return ' '.join(parts)
366
+
367
+ def _progress_throttled(self, every: float = 0.1):
368
+ """Rate-limit UI updates.
369
+
370
+ ``call_from_thread`` blocks the calling worker until the main thread has
371
+ run the callback. Firing it once per hashed file makes the hash pool
372
+ wait on the UI at small-file speed.
373
+ """
374
+ last = [0.0]
375
+
376
+ def _cb(done: int, total: int, current: str = '') -> None:
377
+ now = time.monotonic()
378
+ if done == total or now - last[0] >= every:
379
+ last[0] = now
380
+ self.call_from_thread(self._show_progress, done, total, current)
381
+
382
+ return _cb
383
+
384
+ @work(thread=True, exclusive=True, group='work')
385
+ def _start_scan(self) -> None:
386
+ """Scan both trees, hash, build the table.
387
+
388
+ Worker thread. Every UI touch goes through ``call_from_thread``; every
389
+ piece of domain work goes through ``self._session``.
390
+ """
391
+ try:
392
+ cancel = self._new_cancel_token()
393
+ self._load_cache_step()
394
+ self._resolve_algo_step()
395
+
396
+ self.call_from_thread(self._show_scan_overlay, '⏳ Scanning directories…')
397
+ self.call_from_thread(self._set_summary, '📁 Scanning both sides…')
398
+ try:
399
+ left, right = self._session.scan()
400
+ except OSError as exc:
401
+ self.call_from_thread(self._on_scan_failed, exc)
402
+ return
403
+
404
+ log_info(f'scanned: L={len(left)} R={len(right)} {self._scan_notes(rich=False)}')
405
+ self._report_scan_counts(left, right)
406
+
407
+ entries = self._session.compare(left, right,
408
+ progress_cb=self._progress_throttled(),
409
+ cancel=cancel)
410
+
411
+ log_info(f'done: {len(entries)} entries {self._cache_stats(rich=False)}')
412
+ self.call_from_thread(self._on_scan_complete, entries)
413
+ except Exception:
414
+ # A worker that dies silently leaves _busy stuck and the overlay up.
415
+ log_error('scan worker crashed:\n' + traceback.format_exc())
416
+ self._safe_call(self._on_scan_failed, RuntimeError('internal error — see debug log'))
417
+
418
+ def _load_cache_step(self) -> bool:
419
+ """Open the cache. Returns False if it is unusable. Worker thread."""
420
+ if self._cfg.cache is None or self._session.cache is not None:
421
+ return True
422
+ self.call_from_thread(self.push_screen,
423
+ LoadingScreen(f'Loading cache: {self._cfg.cache.name}…'))
424
+ try:
425
+ self._session.open_cache()
426
+ except DirriftError as exc:
427
+ self.call_from_thread(self._dismiss_loading, '')
428
+ self.call_from_thread(self._cache_unusable, f'cache unusable: {exc}')
429
+ return False
430
+ except (UnicodeDecodeError, OSError) as exc:
431
+ log_error('cache load failed:\n' + traceback.format_exc())
432
+ self.call_from_thread(self._dismiss_loading, '')
433
+ self.call_from_thread(self._cache_unusable, f'cache unreadable ({type(exc).__name__}): {exc}')
434
+ return False
435
+
436
+ n = len(self._session.cache) if self._session.cache else 0
437
+ log_info(f'cache: {n:,} entries')
438
+ if not n:
439
+ log_warning('cache loaded but empty')
440
+ self.call_from_thread(self._dismiss_loading, f'{n:,} cached hashes loaded')
441
+ return True
442
+
443
+ def _resolve_algo_step(self) -> None:
444
+ """Settle on a hash algorithm. Spot-checks read files, so: worker thread."""
445
+ if self._session.cache is None:
446
+ return
447
+ try:
448
+ warning = self._session.resolve_algo()
449
+ except DirriftError as exc:
450
+ self.call_from_thread(self._cache_unusable, str(exc))
451
+ return
452
+ except Exception as exc:
453
+ log_error('cache algo check failed:\n' + traceback.format_exc())
454
+ self.call_from_thread(self._cache_unusable,
455
+ f'cache algorithm check failed ({type(exc).__name__}): {exc}')
456
+ return
457
+ if warning:
458
+ log_warning(f'cache algo warning: {warning}')
459
+ self.call_from_thread(self._refresh_info_bar)
460
+
461
+ def _new_cancel_token(self) -> threading.Event:
462
+ """Fresh token per run; setting the old one asks the previous worker to stop."""
463
+ with self._cancel_lock:
464
+ self._cancel.set()
465
+ self._cancel = threading.Event()
466
+ return self._cancel
467
+
468
+ def _safe_call(self, fn, *args) -> None:
469
+ """``call_from_thread`` that tolerates a shut-down or cancelled app."""
470
+ try:
471
+ self.call_from_thread(fn, *args)
472
+ except Exception: # FIXME: too broad
473
+ dbg(f'call_from_thread({fn.__name__}) failed — app gone?')
474
+
475
+ def _dismiss_loading(self, msg: str) -> None:
476
+ """Pop the LoadingScreen and update status bar."""
477
+ if isinstance(self.screen, LoadingScreen):
478
+ self.pop_screen()
479
+ self._set_summary(msg)
480
+ self._refresh_info_bar()
481
+
482
+ def _report_scan_counts(self, left, right) -> None:
483
+ n = len(set(left) | set(right))
484
+ nh = sum(1 for r in set(left) & set(right)
485
+ if left[r].kind is FileKind.REGULAR
486
+ and right[r].kind is FileKind.REGULAR
487
+ and left[r].size == right[r].size)
488
+ note = self._scan_notes(rich=False)
489
+ note_txt = f' ({note})' if note else ''
490
+ self.call_from_thread(self._set_summary, f'⚡ {n} paths — hashing {nh * 2} files '
491
+ f'({self._algo}, {self._n_workers} threads)…{note_txt}')
492
+
493
+ def _show_progress(self, done: int, total: int, current: str = '') -> None:
494
+ pct = int(done / total * 100) if total else 100
495
+ bar = '█' * (pct // 2) + '░' * (50 - pct // 2)
496
+ cache_str = f' {self._cache_stats()}' if self._cache is not None else ''
497
+ bar_text = as_plain(f'[{bar}] {pct:3d}% {done}/{total}') + cache_str
498
+ self._set_summary(f'⚡ {bar_text} {as_plain(current, Sty.MUTED)}')
499
+ self.query_one('#scan_overlay', ScanOverlay).set_phase(
500
+ '⏳ Hashing in progress', bar_text, as_plain(current, Sty.MUTED))
501
+
502
+ def _on_scan_complete(self, entries: list[FileEntry]) -> None:
503
+ self._all = entries
504
+ self._marked.clear()
505
+ self._scan_done = True
506
+ self._busy = False
507
+
508
+ if self._cache is not None:
509
+ err = self._cache.verify_integrity()
510
+ if err:
511
+ log_error(f'cache integrity check failed: {err}')
512
+ self._cache_note = f'cache modified externally: {err}'
513
+ self.push_screen(ConfirmScreen('Cache file changed while dirrift was running',
514
+ detail=f'{err}\nDigests read from it may not describe the files on disk.',
515
+ action='Continue', show_cancel=False))
516
+
517
+ self._hide_scan_overlay()
518
+
519
+ self._rebuild_table()
520
+ try:
521
+ cache_written = self._session.flush_cache()
522
+ except (OSError, UnicodeError) as exc: # avoid simple app crash on cache write failure
523
+ log_error('cache write failed:\n' + traceback.format_exc())
524
+ cache_written = 0
525
+ self.push_screen(ConfirmScreen('Cache not written',
526
+ detail=f'{exc}\nThe comparison is complete; only the cache update was lost.',
527
+ action='OK', show_cancel=False))
528
+ self._show_summary(cache_written)
529
+
530
+ def _show_summary(self, cache_written: int = 0) -> None:
531
+ c = Counter(e.status for e in self._all)
532
+ total = len(self._all)
533
+ parts: list[str] = []
534
+ if self._file_ops.dry_run:
535
+ parts.append(styled('DRY-RUN', Sty.ERR))
536
+ parts.append(f'{styled(f"{total:,}", Sty.ACCENT)} files:')
537
+ parts.extend([
538
+ styled(f'≠ {c[FileStatus.DIFFERENT]}', Sty.ST_DIFF),
539
+ styled(f'← {c[FileStatus.LEFT_ONLY]}', Sty.ST_LEFT),
540
+ styled(f'→ {c[FileStatus.RIGHT_ONLY]}', Sty.ST_RIGHT),
541
+ styled(f'≡ {c[FileStatus.IDENTICAL]}', Sty.ST_SAME),
542
+ ])
543
+ if c[FileStatus.ERROR]:
544
+ parts.append(styled(f'✗ {c[FileStatus.ERROR]}', Sty.ST_ERROR))
545
+ parts.append(self._similarity_bar(c, total))
546
+ subset = self._subset_relation()
547
+ if subset:
548
+ parts.append(subset)
549
+ if self._cache is not None:
550
+ parts.append(self._cache_stats())
551
+ if cache_written:
552
+ parts.append(styled(f'+{cache_written} cached', Sty.OK))
553
+ note = self._scan_notes()
554
+ if note:
555
+ parts.append(note)
556
+ self._set_summary(' '.join(parts))
557
+
558
+ @staticmethod
559
+ def _similarity_bar(counts: Counter, total: int) -> str:
560
+ """Colored proportional bar showing status breakdown — see ``summary``."""
561
+ return similarity_bar(counts, total)
562
+
563
+ # ── table ─────────────────────────────────────────────────────────────
564
+ def _rebuild_table(self) -> None:
565
+ t = self.query_one(DataTable)
566
+ cursor_row = t.cursor_row if t.row_count > 0 else 0
567
+ t.clear()
568
+
569
+ if self._view_mode is ViewMode.TREE:
570
+ items = self._build_tree_items()
571
+ self._visible = items
572
+ row_fn = self._tree_row
573
+ else:
574
+ self._visible = [e for e in self._all if self._show_same or e.status != FileStatus.IDENTICAL]
575
+ if self._filter_pattern:
576
+ try:
577
+ rx = re.compile(self._filter_pattern, re.IGNORECASE)
578
+ self._visible = [e for e in self._visible if rx.search(e.rel_path)]
579
+ except re.error:
580
+ # fall back to plain substring
581
+ needle = self._filter_pattern.lower()
582
+ self._visible = [e for e in self._visible if needle in e.rel_path.lower()]
583
+ self._sort_visible()
584
+ row_fn = self._entry_row
585
+
586
+ for item in self._visible:
587
+ marked = isinstance(item, FileEntry) and item.rel_path in self._marked
588
+ key = f'dir:{item.rel_path}' if isinstance(item, DirNode) else item.rel_path
589
+ t.add_row(*row_fn(item, marked), key=key)
590
+
591
+ if self._visible:
592
+ t.move_cursor(row=min(cursor_row, len(self._visible) - 1))
593
+ self._refresh_info_bar()
594
+
595
+ def _subset_relation(self) -> str | None:
596
+ """Detect when one tree is a perfect subset of the other — see ``summary``."""
597
+ return subset_relation(Counter(e.status for e in self._all))
598
+
599
+ def _sort_visible(self) -> None:
600
+ """Sort self._visible according to current sort column and direction."""
601
+ if self._view_mode is ViewMode.TREE:
602
+ return # tree mode has its own ordering
603
+ key_name = SORT_KEYS[self._sort_col][0]
604
+ key_func = {
605
+ 'status': lambda e: (STATUS_ORDER[e.status], e.rel_path),
606
+ 'path': lambda e: e.rel_path.lower(),
607
+ 'left_size': lambda e: (e.left_size if e.left_size is not None else -1),
608
+ 'right_size': lambda e: (e.right_size if e.right_size is not None else -1),
609
+ 'left_mtime': lambda e: (e.left_mtime or 0.0),
610
+ 'right_mtime': lambda e: (e.right_mtime or 0.0),
611
+ }[key_name]
612
+ self._visible.sort(key=key_func, reverse=self._sort_rev)
613
+
614
+ @staticmethod
615
+ def _entry_row(entry: FileEntry, marked: bool = False) -> tuple[Text, ...]:
616
+ s = sty(STATUS_STYLE[entry.status])
617
+ if marked:
618
+ s += ' reverse'
619
+ mark = '▸' if marked else ' '
620
+ return (
621
+ Text(f'{mark}{STATUS_ICON[entry.status]}', style=s),
622
+ Text(entry.rel_path, style=s),
623
+ Text(fmt_size(entry.left_size), justify='right', style=s),
624
+ Text(fmt_size(entry.right_size), justify='right', style=s),
625
+ Text(fmt_mtime(entry.left_mtime), style=s),
626
+ Text(fmt_mtime(entry.right_mtime), style=s),
627
+ )
628
+
629
+ def _tree_row(self, item: DirNode | FileEntry, marked: bool = False) -> tuple[Text, ...]:
630
+ if isinstance(item, DirNode):
631
+ indent = ' ' * item.depth
632
+ icon = '▶' if item.rel_path in self._collapsed else '▼'
633
+ summary = self._dir_summary_text(item.counts)
634
+ bold = sty(Sty.ACCENT)
635
+ return (Text(summary, style=bold),
636
+ Text(f'{indent}{icon} {item.name}/', style=bold),
637
+ Text(''), Text(''), Text(''), Text(''))
638
+ else: # file
639
+ s = sty(STATUS_STYLE[item.status])
640
+ if marked:
641
+ s += ' reverse'
642
+ mark = '▸' if marked else ' '
643
+ depth = item.rel_path.count('/')
644
+ indent = ' ' * depth
645
+ name = item.rel_path.rsplit('/', 1)[-1]
646
+ icon = STATUS_ICON[item.status]
647
+ return (Text(f'{mark}{icon}', style=s),
648
+ Text(f'{indent}{name}', style=s),
649
+ Text(fmt_size(item.left_size), justify='right', style=s),
650
+ Text(fmt_size(item.right_size), justify='right', style=s),
651
+ Text(fmt_mtime(item.left_mtime), style=s),
652
+ Text(fmt_mtime(item.right_mtime), style=s))
653
+
654
+ @staticmethod
655
+ def _dir_summary_text(counts: Counter) -> str:
656
+ return ' '.join(f'{glyph}{counts[status]}' for status, glyph in SUMMARY_GLYPHS if counts[status])
657
+
658
+ def _update_row(self, entry: FileEntry) -> None:
659
+ """Update a single row's cells without full table rebuild."""
660
+ t = self.query_one(DataTable)
661
+ marked = entry.rel_path in self._marked
662
+ if self._view_mode is ViewMode.TREE:
663
+ cells = self._tree_row(entry, marked)
664
+ else:
665
+ cells = self._entry_row(entry, marked)
666
+ for key, val in zip(COL_KEYS, cells):
667
+ t.update_cell(entry.rel_path, key, val)
668
+
669
+ def _set_summary(self, msg: str | Text) -> None:
670
+ """Update the summary bar.
671
+
672
+ A ``Text`` is rendered verbatim — no markup parsing, so filenames are
673
+ safe by construction. A ``str`` is markup and must already be escaped.
674
+ """
675
+ self.query_one('#summary_bar', Static).update(msg)
676
+
677
+ @staticmethod
678
+ def _line(*parts: tuple[str, Sty | None]) -> Text:
679
+ """Assemble a summary line from (text, role) pairs. Nothing is parsed."""
680
+ out = Text()
681
+ for text, role in parts:
682
+ out.append(text, style=sty(role) if role else '')
683
+ out.append(' ')
684
+ return out
685
+
686
+ def _selected(self) -> FileEntry | None:
687
+ item = self._current_item()
688
+ return item if isinstance(item, FileEntry) else None
689
+
690
+ def _get_action_target_entries(self) -> list[FileEntry]:
691
+ """Return marked entries, or children of selected dir, or single selected file."""
692
+ if self._marked:
693
+ return [e for e in self._all if e.rel_path in self._marked]
694
+ item = self._current_item()
695
+ if isinstance(item, DirNode):
696
+ prefix = item.rel_path + '/'
697
+ return [e for e in self._all if e.rel_path.startswith(prefix)]
698
+ if isinstance(item, FileEntry):
699
+ return [item]
700
+ return []
701
+
702
+ # ── navigation ────────────────────────────────────────────────────────
703
+ def action_cursor_down(self) -> None:
704
+ if not self._visible:
705
+ return
706
+ t = self.query_one(DataTable)
707
+ t.move_cursor(row=min(t.cursor_row + 1, len(self._visible) - 1))
708
+
709
+ def action_cursor_up(self) -> None:
710
+ if not self._visible:
711
+ return
712
+ t = self.query_one(DataTable)
713
+ t.move_cursor(row=max(t.cursor_row - 1, 0))
714
+
715
+ def action_goto_top(self) -> None:
716
+ if self._visible:
717
+ self.query_one(DataTable).move_cursor(row=0)
718
+
719
+ def action_goto_bottom(self) -> None:
720
+ if self._visible:
721
+ self.query_one(DataTable).move_cursor(row=len(self._visible) - 1)
722
+
723
+ # ── marking (selection) ───────────────────────────────────────────────
724
+ def action_toggle_mark(self) -> None:
725
+ """Toggle mark on current row, (or children of dir) then move cursor down."""
726
+ item = self._current_item()
727
+ if item is None:
728
+ return
729
+ if isinstance(item, DirNode):
730
+ prefix = item.rel_path + '/'
731
+ children = {e.rel_path for e in self._all if e.rel_path.startswith(prefix)}
732
+ if children <= self._marked:
733
+ self._marked -= children # all marked → unmark
734
+ else:
735
+ self._marked |= children # some/none → mark all
736
+ self._rebuild_table()
737
+ return
738
+ self._marked.symmetric_difference_update({item.rel_path})
739
+ self._update_row(item)
740
+ self._refresh_info_bar()
741
+ self.action_cursor_down()
742
+
743
+ def action_mark_down(self) -> None:
744
+ """Mark current row and move cursor down (shift+j / ranger style)."""
745
+ e = self._selected()
746
+ if e is None:
747
+ return
748
+ self._marked.add(e.rel_path)
749
+ self._update_row(e)
750
+ self._refresh_info_bar()
751
+ self.action_cursor_down()
752
+
753
+ def action_mark_up(self) -> None:
754
+ """Mark current row and move cursor up (shift+k / ranger style)."""
755
+ e = self._selected()
756
+ if e is None:
757
+ return
758
+ self._marked.add(e.rel_path)
759
+ self._update_row(e)
760
+ self._refresh_info_bar()
761
+ self.action_cursor_up()
762
+
763
+ def action_unmark_all(self) -> None:
764
+ """Clear all marks."""
765
+ if not self._marked:
766
+ return
767
+ self._marked.clear()
768
+ self._rebuild_table()
769
+
770
+ # ── toggle display mode (tree <-> list) ──────────────────────────────
771
+ def action_toggle_view(self) -> None:
772
+ self._view_mode = ViewMode.TREE if self._view_mode is ViewMode.LIST else ViewMode.LIST
773
+ self._setup_columns()
774
+ self._rebuild_table()
775
+
776
+ def _setup_columns(self) -> None:
777
+ t = self.query_one(DataTable)
778
+ t.clear(columns=True)
779
+ t.add_column('Status', width=10, key='col_status')
780
+ t.add_column('Path', key='col_path')
781
+ t.add_column('L Size', width=12, key='col_lsize')
782
+ t.add_column('R Size', width=12, key='col_rsize')
783
+ t.add_column('L mtime', width=18, key='col_lmtime')
784
+ t.add_column('R mtime', width=18, key='col_rmtime')
785
+
786
+ def _build_tree_items(self) -> list[DirNode | FileEntry]:
787
+ """Interleave dir nodes with file entries, respecting collapse state."""
788
+ entries = [e for e in self._all if self._show_same or e.status != FileStatus.IDENTICAL]
789
+ if self._filter_pattern:
790
+ try:
791
+ rx = re.compile(self._filter_pattern, re.IGNORECASE)
792
+ entries = [e for e in entries if rx.search(e.rel_path)]
793
+ except re.error:
794
+ needle = self._filter_pattern.lower()
795
+ entries = [e for e in entries if needle in e.rel_path.lower()]
796
+ entries.sort(key=lambda e: e.rel_path)
797
+
798
+ # collect status counts per directory
799
+ dir_counts: dict[str, Counter] = {}
800
+ for e in entries:
801
+ parts = e.rel_path.split('/')
802
+ for i in range(1, len(parts)):
803
+ d = '/'.join(parts[:i])
804
+ if d not in dir_counts:
805
+ dir_counts[d] = Counter()
806
+ dir_counts[d][e.status] += 1
807
+
808
+ result: list[DirNode | FileEntry] = []
809
+ emitted_dirs: set[str] = set()
810
+
811
+ for e in entries:
812
+ parts = e.rel_path.split('/')
813
+ hidden = False
814
+ for i in range(1, len(parts)):
815
+ d = '/'.join(parts[:i])
816
+ if d not in emitted_dirs:
817
+ emitted_dirs.add(d)
818
+ result.append(DirNode(d, i - 1, dir_counts[d]))
819
+ if d in self._collapsed:
820
+ hidden = True
821
+ break
822
+ if not hidden:
823
+ result.append(e)
824
+
825
+ return result
826
+
827
+ def action_toggle_node(self) -> None: # FIXME: bind
828
+ item = self._current_item()
829
+ if not isinstance(item, DirNode):
830
+ return
831
+ self._collapsed.symmetric_difference_update({item.rel_path})
832
+ self._rebuild_table()
833
+
834
+ def action_expand_node(self) -> None:
835
+ """Expand current dir node. In list mode, scroll right as the table would."""
836
+ if self._view_mode is not ViewMode.TREE:
837
+ self.query_one(DataTable).action_scroll_right()
838
+ return
839
+ item = self._current_item()
840
+ if isinstance(item, DirNode) and item.rel_path in self._collapsed:
841
+ self._collapsed.discard(item.rel_path)
842
+ self._rebuild_table()
843
+
844
+ def action_expand_all(self) -> None:
845
+ self._collapsed.clear()
846
+ self._rebuild_table()
847
+
848
+ def action_collapse_node(self) -> None:
849
+ """Collapse current dir, or navigate to parent dir and collapse it. In list mode, scroll left."""
850
+ if self._view_mode is not ViewMode.TREE:
851
+ self.query_one(DataTable).action_scroll_left()
852
+ return
853
+ item = self._current_item()
854
+ if isinstance(item, DirNode) and item.rel_path not in self._collapsed:
855
+ self._collapsed.add(item.rel_path)
856
+ self._rebuild_table()
857
+ return
858
+ # file or already-collapsed dir → find parent, collapse it
859
+ path = item.rel_path if item else ''
860
+ if '/' in path:
861
+ parent = path.rsplit('/', 1)[0]
862
+ self._collapsed.add(parent)
863
+ self._rebuild_table()
864
+ # move cursor to the parent dir row
865
+ for i, v in enumerate(self._visible):
866
+ if isinstance(v, DirNode) and v.rel_path == parent:
867
+ self.query_one(DataTable).move_cursor(row=i)
868
+ break
869
+
870
+ def action_collapse_all(self) -> None:
871
+ self._collapsed = {item.rel_path for item in self._visible if isinstance(item, DirNode)}
872
+ self._rebuild_table()
873
+
874
+ def _current_item(self) -> DirNode | FileEntry | None:
875
+ t = self.query_one(DataTable)
876
+ r = t.cursor_row
877
+ return self._visible[r] if 0 <= r < len(self._visible) else None
878
+
879
+ # ── sorting ───────────────────────────────────────────────────────────
880
+ def action_sort_next(self) -> None:
881
+ """Cycle to the next sort column; reset direction on column change."""
882
+ prev = self._sort_col
883
+ self._sort_col = (self._sort_col + 1) % len(SORT_KEYS)
884
+ self._sort_rev = not self._sort_rev if self._sort_col == prev else False
885
+ self._rebuild_table()
886
+
887
+ def action_sort_reverse(self) -> None:
888
+ """Reverse current sort direction."""
889
+ self._sort_rev = not self._sort_rev
890
+ self._rebuild_table()
891
+
892
+ # ── filtering ───────────────────────────────────────────────────────────
893
+ def action_filter(self) -> None:
894
+ self.push_screen(InputModal('Filter', self._filter_pattern,
895
+ 'Enter → apply empty → clear Esc → cancel'),
896
+ self._apply_filter) # type: ignore[arg-type]
897
+
898
+ def _apply_filter(self, pattern: str) -> None:
899
+ self._filter_pattern = pattern
900
+ self._rebuild_table()
901
+
902
+ # ── searching ───────────────────────────────────────────────────────────
903
+ def action_search(self) -> None:
904
+ self.push_screen(InputModal('Search', self._search_pattern,
905
+ 'Enter → jump n/N → next/prev Esc → cancel'),
906
+ self._apply_search) # type: ignore[arg-type]
907
+
908
+ def _apply_search(self, pattern: str) -> None:
909
+ self._search_pattern = pattern
910
+ self._jump_to_match(forward=True)
911
+
912
+ def action_search_next(self) -> None:
913
+ self._jump_to_match(forward=True)
914
+
915
+ def action_search_prev(self) -> None:
916
+ self._jump_to_match(forward=False)
917
+
918
+ def _jump_to_match(self, forward: bool) -> None:
919
+ if not self._search_pattern:
920
+ return
921
+ try:
922
+ rx = re.compile(self._search_pattern, re.IGNORECASE)
923
+ except re.error:
924
+ rx = None
925
+ t = self.query_one(DataTable)
926
+ start = t.cursor_row
927
+ rows = list(range(len(self._visible)))
928
+ ordered = rows[start + 1:] + rows[:start + 1] if forward else rows[:start][::-1] + rows[start:][::-1]
929
+ for i in ordered:
930
+ name = self._visible[i].rel_path
931
+ hit = rx.search(name) if rx else self._search_pattern.lower() in name.lower()
932
+ if hit:
933
+ t.move_cursor(row=i)
934
+ return
935
+
936
+ # ── toggle / rescan / help / quit ─────────────────────────────────────
937
+ def action_toggle_same(self) -> None:
938
+ self._show_same = not self._show_same
939
+ self._rebuild_table()
940
+
941
+ def action_rescan(self) -> None:
942
+ if not self._claim('rescan'):
943
+ return
944
+ self._all, self._visible = [], []
945
+ self._marked.clear()
946
+ self._cache_note = None
947
+ self._scan_done = False
948
+ self.query_one(DataTable).clear()
949
+ self._start_scan()
950
+
951
+ def action_help(self) -> None:
952
+ self.push_screen(HelpScreen(HELP_PAGES))
953
+
954
+ def action_quit(self) -> None:
955
+ """Exit code: 0 identical, 1 differences, 2 no completed comparison."""
956
+ self._new_cancel_token()
957
+ if self._busy and self._scan_done:
958
+ # A batch is mid-flight: files are being written right now.
959
+ if self._quit_warned:
960
+ self.exit(return_code=2) # abandoned mid-batch: the comparison no longer matches the disk
961
+ return
962
+ self._quit_warned = True
963
+ self._set_summary(styled('operation in progress — press q again to abandon',
964
+ Sty.WARN))
965
+ return
966
+ if not self._scan_done:
967
+ self.exit(return_code=2) # never claim "identical" for an abandoned scan
968
+ return
969
+ has_diff = any(e.status is not FileStatus.IDENTICAL for e in self._all)
970
+ self.exit(return_code=1 if has_diff else 0)
971
+
972
+ # ══════════════════════════════════════════════════════════════════════
973
+ # PARALLEL BATCH FRAMEWORK — replaces the three _do_*_batch methods
974
+ # ══════════════════════════════════════════════════════════════════════
975
+
976
+ def _start_batch(self, tasks: list[BatchTask], op_name: str, verb_past: str) -> None:
977
+ """Main thread: claim the work slot, then hand off to the worker."""
978
+ if not tasks:
979
+ return
980
+ if not self._claim(op_name.lower()):
981
+ return
982
+ self._run_batch(tasks, op_name, verb_past)
983
+
984
+ # WARNING: call_from_thread means call from main (TUI) thread not worker thread
985
+ @work(thread=True, exclusive=True, group='work') # same group as _start_scan
986
+ def _run_batch(self, tasks: list[BatchTask], op_name: str, verb_past: str) -> None:
987
+ """Execute *tasks* in parallel with progress overlay.
988
+
989
+ I/O (preflight + execute) runs in worker threads.
990
+ State mutations (on_success) are collected and applied on the main thread.
991
+ """
992
+ try:
993
+ total = len(tasks)
994
+ self.call_from_thread(self._show_scan_overlay, f'⏳ {op_name} {total} file(s)…')
995
+ done_count, lock = [0], threading.Lock()
996
+ abort = threading.Event() # set once the trees turn out to share storage
997
+
998
+ def _worker(idx_task: tuple[int, BatchTask]) -> tuple[int, bool, str | None]:
999
+ idx, task = idx_task
1000
+ if abort.is_set():
1001
+ return idx, False, ABORTED
1002
+ err = self._file_ops.preflight_all(task.checks)
1003
+ if err:
1004
+ return idx, False, f'{STALE}{err}'
1005
+ try:
1006
+ task.execute()
1007
+ return idx, True, None
1008
+ except AliasError as exc:
1009
+ abort.set() # every remaining delete would hit the same thing
1010
+ log_error(f'{op_name} stopped: {task.label}: {exc}')
1011
+ return idx, False, f'{task.label}: {exc}'
1012
+ except (OSError, RuntimeError) as exc:
1013
+ log_error(f'{op_name} failed: {task.label}: {exc}')
1014
+ return idx, False, f'{task.label}: {exc}'
1015
+
1016
+ def _wrapped(idx_task: tuple[int, BatchTask]) -> tuple[int, bool, str | None]:
1017
+ result = _worker(idx_task)
1018
+ with lock:
1019
+ done_count[0] += 1
1020
+ n = done_count[0]
1021
+ self._safe_call(self._show_batch_progress, n, total, op_name, idx_task[1].label)
1022
+ return result
1023
+
1024
+ with ThreadPoolExecutor(max_workers=self._n_workers) as pool:
1025
+ results = list(pool.map(_wrapped, enumerate(tasks)))
1026
+
1027
+ n_pruned = self._prune_after_batch(tasks, results) # still in the worker
1028
+ self.call_from_thread(self._finish_batch, tasks, results, verb_past, n_pruned)
1029
+ except Exception:
1030
+ log_error(f'{op_name} worker crashed:\n' + traceback.format_exc())
1031
+ self._safe_call(self._on_batch_failed, 'internal error — see debug log')
1032
+
1033
+ def _on_batch_failed(self, msg: str) -> None:
1034
+ self._busy = False
1035
+ self._quit_warned = False
1036
+ self._hide_scan_overlay()
1037
+ self._set_summary(fmt('✗ batch failed: {}', msg, role=Sty.ERR))
1038
+
1039
+ def _show_batch_progress(self, done: int, total: int, op_name: str, current: str) -> None:
1040
+ pct = int(done / total * 100) if total else 100
1041
+ bar = '█' * (pct // 2) + '░' * (50 - pct // 2)
1042
+ bar_text = as_plain(f'[{bar}] {pct:3d}% {done}/{total}')
1043
+ self.query_one('#scan_overlay', ScanOverlay).set_phase(
1044
+ f'⏳ {op_name}…', bar_text, as_plain(current, Sty.MUTED))
1045
+
1046
+ def _drop_vanished_entries(self) -> None:
1047
+ """Forget entries (**rows**) whose file is now gone from both sides."""
1048
+ self._all = [e for e in self._all if e.left_path is not None or e.right_path is not None]
1049
+
1050
+ def _finish_batch(self, tasks: list[BatchTask],
1051
+ results: list[tuple[int, bool, str | None]],
1052
+ verb_past: str, n_pruned: int = 0) -> None:
1053
+ """Apply on_success callbacks & show summary (main thread only)."""
1054
+ ok = fail = stale = aborted = 0
1055
+ errors: list[str] = []
1056
+ for (_, success, error), task in zip(results, tasks):
1057
+ if success:
1058
+ try:
1059
+ task.on_success()
1060
+ except Exception as exc: # a rescan may have replaced self._all
1061
+ log_error(f'on_success failed for {task.label}: {exc!r}')
1062
+ errors.append(f'{task.label}: bookkeeping failed ({exc})')
1063
+ ok += 1
1064
+ elif error == ABORTED:
1065
+ aborted += 1
1066
+ elif error and error.startswith(STALE):
1067
+ stale += 1
1068
+ else:
1069
+ fail += 1
1070
+ if error:
1071
+ errors.append(error)
1072
+
1073
+ self._busy = False
1074
+ self._quit_warned = False # the batch the warning was about is over
1075
+
1076
+ # prune rows (files) where both sides are now gone
1077
+ self._drop_vanished_entries()
1078
+ self._marked.clear()
1079
+ self._hide_scan_overlay()
1080
+ self._rebuild_table()
1081
+
1082
+ msg = styled(f'✓ {ok} {verb_past}', Sty.OK)
1083
+ if n_pruned:
1084
+ msg += ' ' + styled(f'⌫ {n_pruned} empty dir(s) removed', Sty.MUTED)
1085
+ if stale:
1086
+ msg += ' ' + styled(f'⚠ {stale} changed — skipped', Sty.WARN)
1087
+ if fail:
1088
+ msg += ' ' + styled(f'✗ {fail} failed', Sty.ERR)
1089
+ if aborted:
1090
+ msg += ' ' + styled(f'⛔ stopped — {aborted} not attempted', Sty.ERR)
1091
+ self._set_summary(msg)
1092
+ if aborted:
1093
+ self.push_screen(ConfirmScreen('Batch stopped: both sides are the same storage',
1094
+ detail=(f'{aborted:,} remaining operation(s) were not attempted.\n'
1095
+ f'The left and right copies of a file turned out to be one file '
1096
+ f'(bind mount, second mount of one share, or a followed symlink). '
1097
+ f'Rescan, and check the two roots before deleting anything else.'),
1098
+ paths=errors[:200], action='OK', show_cancel=False))
1099
+ elif errors:
1100
+ self.push_screen(ConfirmScreen(f'{fail} operation(s) failed',
1101
+ paths=errors[:200], action='OK', show_cancel=False))
1102
+
1103
+ # ── on_success helpers (main thread only) ─────────────────────────────
1104
+
1105
+ def _clear_side(self, entry: FileEntry, side: Side) -> None:
1106
+ """Null out the deleted side and recompute file status."""
1107
+ entry.set_side(side, path=None, size=None, mtime=None)
1108
+ if entry.left_path:
1109
+ entry.status = FileStatus.LEFT_ONLY
1110
+ elif entry.right_path:
1111
+ entry.status = FileStatus.RIGHT_ONLY
1112
+
1113
+ def _copy_on_success(self, entry: FileEntry, dst: Path, src_side: Side) -> None:
1114
+ """After successful copy: fill the missing side from the source side."""
1115
+ dst_side = Side.RIGHT if src_side is Side.LEFT else Side.LEFT
1116
+ entry.set_side(dst_side, path=dst, size=entry.side_size(src_side), mtime=entry.side_mtime(src_side))
1117
+ entry.status = FileStatus.IDENTICAL
1118
+
1119
+ def _resolve_on_success(self, entry: FileEntry, keep: Side) -> None:
1120
+ """After successful resolve: equalise both sides from *keep*."""
1121
+ lose = Side.RIGHT if keep is Side.LEFT else Side.LEFT
1122
+ entry.set_side(lose, size=entry.side_size(keep), mtime=entry.side_mtime(keep))
1123
+ entry.status = FileStatus.IDENTICAL
1124
+
1125
+ def _keep_both_on_success(self, entry: FileEntry, left_name: str, right_name: str) -> None:
1126
+ """Replace one DIFFERENT entry with two IDENTICAL entries."""
1127
+ try:
1128
+ self._all.remove(entry)
1129
+ except ValueError: # a rescan replaced _all under us
1130
+ dbg(f'keep_both: {entry.rel_path} no longer in _all')
1131
+ return
1132
+ parent = Path(entry.rel_path).parent
1133
+ for name in (left_name, right_name):
1134
+ rel = str(parent / name) if str(parent) != '.' else name
1135
+ l_path, r_path = self.left_dir / rel, self.right_dir / rel
1136
+ try:
1137
+ st = l_path.stat()
1138
+ sz, mt = st.st_size, st.st_mtime
1139
+ except OSError:
1140
+ sz, mt = None, None
1141
+ self._all.append(FileEntry(
1142
+ rel_path=rel, status=FileStatus.IDENTICAL,
1143
+ left_path=l_path, right_path=r_path,
1144
+ left_size=sz, right_size=sz,
1145
+ left_mtime=mt, right_mtime=mt,
1146
+ left_kind=FileKind.REGULAR, right_kind=FileKind.REGULAR,
1147
+ ))
1148
+
1149
+ # ══════════════════════════════════════════════════════════════════════
1150
+ # ACTIONS → build BatchTask lists → _start_batch
1151
+ # ══════════════════════════════════════════════════════════════════════
1152
+
1153
+ def _format_transfers(self, items: list[tuple[FileEntry, Path, Path]]) -> list[str]:
1154
+ return [f'{src} → {dst}' for _, src, dst in items]
1155
+
1156
+ def _guard_dry_run(self, action: str) -> bool:
1157
+ """Show dry-run warning and return True if mutations are blocked."""
1158
+ if self._file_ops.dry_run:
1159
+ self._set_summary(styled(f'dry-run mode — {action} disabled', Sty.WARN))
1160
+ return True
1161
+ return False
1162
+
1163
+ # ── delete ────────────────────────────────────────────────────────────
1164
+ def action_del_left(self) -> None:
1165
+ self._request_delete(Side.LEFT)
1166
+
1167
+ def action_del_right(self) -> None:
1168
+ self._request_delete(Side.RIGHT)
1169
+
1170
+ def _request_delete(self, side: Side) -> None:
1171
+ if self._guard_dry_run('deletion'):
1172
+ return
1173
+ targets, refused = self._actionable(self._get_action_target_entries(), side)
1174
+ deletable = [(e, e.side_path(side)) for e in targets if e.side_path(side) is not None]
1175
+ if not deletable:
1176
+ self._warn_refused(refused, 'deleted')
1177
+ return
1178
+ paths = [str(p) for _, p in deletable]
1179
+ total = self._sum_sizes(e.side_size(side) for e, _ in deletable)
1180
+ entries = [e for e, _ in deletable]
1181
+ lines = delete_breakdown(entries, side) + self._selection_notes(entries, refused)
1182
+ if self._prune_empty:
1183
+ lines.append('Empty directories will also be removed.')
1184
+ detail = '\n'.join(lines)
1185
+ title = f'Permanently delete {len(paths)} file(s) from {styled(side.label, Sty.ACCENT)}?'
1186
+ self.push_screen(ConfirmScreen(title, detail, action='Delete',
1187
+ paths=paths, total_bytes=total),
1188
+ callback=lambda ok: ok and self._do_delete(deletable, side))
1189
+
1190
+ def _selection_notes(self, entries: list[FileEntry], refused: int) -> list[str]:
1191
+ """Confirm-dialog caveats about the selection — see ``summary.selection_notes``."""
1192
+ shown = {v.rel_path for v in self._visible if isinstance(v, FileEntry)}
1193
+ n_hidden = sum(1 for e in entries if e.rel_path not in shown)
1194
+ return selection_notes(n_hidden=n_hidden, n_refused=refused)
1195
+
1196
+ def _do_delete(self, items: list[tuple[FileEntry, Path]], side: Side) -> None:
1197
+ tasks = []
1198
+ for e, p in items:
1199
+ # An IDENTICAL entry is deleted *because* the other side has it. That
1200
+ # twin must still be exactly as scanned (a stat, not a re-hash), and
1201
+ # must not be this very file seen through a second path.
1202
+ twin = e.side_path(side.other) if e.status is FileStatus.IDENTICAL else None
1203
+ checks = (self._unchanged_since_scan(e, side),)
1204
+ if twin is not None:
1205
+ checks += (self._unchanged_since_scan(e, side.other),)
1206
+ tasks.append(BatchTask(entry=e, checks=checks, execute=partial(self._file_ops.delete, p, twin=twin),
1207
+ on_success=partial(self._clear_side, e, side), label=p.name, prune_from=p.parent))
1208
+ self._start_batch(tasks, f'Deleting from {side.label}', 'deleted')
1209
+
1210
+ def _prune_after_batch(self, tasks: list[BatchTask],
1211
+ results: list[tuple[int, bool, str | None]]) -> int:
1212
+ """Remove directories emptied by this batch. Worker thread — no UI calls."""
1213
+ if not self._prune_empty or self._file_ops.dry_run:
1214
+ return 0
1215
+ candidates = {task.prune_from for (_, ok, _), task in zip(results, tasks)
1216
+ if ok and task.prune_from is not None}
1217
+ # Deepest root first: with overlapping trees (right inside left) a path is
1218
+ # relative to both, and the correct stop_at is the *nearer* root.
1219
+ roots = sorted(((Side.LEFT, self.left_dir), (Side.RIGHT, self.right_dir)),
1220
+ key=lambda sr: len(sr[1].parts), reverse=True)
1221
+ removed = 0
1222
+ # Deepest directory first: emptying a child can empty its parent.
1223
+ for d in sorted(candidates, key=lambda p: len(p.parts), reverse=True):
1224
+ for _side, root in roots:
1225
+ if d.is_relative_to(root):
1226
+ removed += len(self._file_ops.prune_empty_dirs(d, stop_at=root))
1227
+ break
1228
+ return removed
1229
+
1230
+ # ── copy missing ──────────────────────────────────────────────────────
1231
+ def action_copy_missing(self) -> None:
1232
+ """Copy file(s) to whichever side is missing."""
1233
+ if self._guard_dry_run('copy'):
1234
+ return
1235
+ targets = self._get_action_target_entries()
1236
+ targets, refused = self._actionable(targets, Side.LEFT, Side.RIGHT)
1237
+ copyable: list[tuple[FileEntry, Path, Path, Side]] = []
1238
+ for e in targets:
1239
+ if e.status == FileStatus.LEFT_ONLY and e.left_path:
1240
+ copyable.append((e, e.left_path, self.right_dir / e.rel_path, Side.LEFT))
1241
+ elif e.status == FileStatus.RIGHT_ONLY and e.right_path:
1242
+ copyable.append((e, e.right_path, self.left_dir / e.rel_path, Side.RIGHT))
1243
+ if not copyable:
1244
+ if any(e.status == FileStatus.DIFFERENT for e in targets):
1245
+ self._set_summary(styled('both sides differ — use < or > to resolve', Sty.WARN))
1246
+ return
1247
+ self._warn_refused(refused, 'copied')
1248
+ transfer_items = [(e, src, dst) for e, src, dst, _ in copyable]
1249
+ paths = self._format_transfers(transfer_items)
1250
+ total = self._sum_sizes(e.side_size(src_side) for e, _, _, src_side in copyable)
1251
+ self.push_screen(ConfirmScreen(f'Copy {len(paths)} file(s) to missing side?',
1252
+ action='Copy', paths=paths, total_bytes=total),
1253
+ callback=lambda ok: ok and self._do_copy(copyable))
1254
+
1255
+ def _do_copy(self, items: list[tuple[FileEntry, Path, Path, Side]]) -> None:
1256
+ tasks = []
1257
+ for e, src, dst, src_side in items:
1258
+ dst_side = src_side.other
1259
+ tasks.append(BatchTask(
1260
+ entry=e,
1261
+ checks=(self._unchanged_since_scan(e, src_side), MutationRequirement.absent(dst)),
1262
+ execute=partial(self._file_ops.copy, src, dst, verify_hash=self._algo,
1263
+ follow_symlinks=self._deref, confine_to=self._confinement_root(dst_side)),
1264
+ on_success=partial(self._copy_on_success, e, dst, src_side),
1265
+ label=src.name,
1266
+ ))
1267
+ self._start_batch(tasks, 'Copying', 'copied')
1268
+
1269
+ def _unchanged_since_scan(self, entry: FileEntry, side: Side) -> MutationRequirement:
1270
+ """What must still hold for one side of *entry* before it is changed."""
1271
+ return MutationRequirement.unchanged_since_scan(entry, side, follow_symlinks=self._deref)
1272
+
1273
+ def _confinement_root(self, side: Side) -> Path | None:
1274
+ """Root a copy into *side* must stay inside, or None when links are part of the tree.
1275
+
1276
+ Under ``--symlinks safe`` / ``always`` a followed directory link was walked
1277
+ and its files are entries of the tree: writing through it is expected.
1278
+ """
1279
+ if self._deref:
1280
+ return None
1281
+ return self.left_dir if side is Side.LEFT else self.right_dir
1282
+
1283
+ # Display diffs
1284
+
1285
+ def action_open_diff(self) -> None:
1286
+ e = self._selected()
1287
+ if e is None or e.status != FileStatus.DIFFERENT:
1288
+ self._set_summary(styled('select a DIFFERENT file to open in diff tool', Sty.WARN))
1289
+ return
1290
+ left, right = e.left_path, e.right_path # capture before dismiss
1291
+ if not is_text_file(left) or not is_text_file(right):
1292
+ self._set_summary(styled('binary file — diff not available', Sty.WARN))
1293
+ return
1294
+ self.push_screen(DiffToolScreen(left, right),
1295
+ lambda cmd: cmd and self._launch_diff(cmd, left, right))
1296
+
1297
+ def _launch_diff(self, cmd: str, left: Path, right: Path) -> None:
1298
+ if not left or not right:
1299
+ self._set_summary(styled('both sides needed for diff', Sty.WARN))
1300
+ return
1301
+ for p in (left, right):
1302
+ if not p.exists():
1303
+ self._set_summary(self._line(('file gone: ', None), (p.name, Sty.ERR)))
1304
+ return
1305
+
1306
+ argv = shlex.split(cmd) + [str(left), str(right)]
1307
+ prog = Path(argv[0]).stem
1308
+
1309
+ try:
1310
+ if prog in _TUI_PROGS: # give back the terminal, run in foreground, resume TUI after
1311
+ with self.suspend():
1312
+ subprocess.run(argv)
1313
+
1314
+ elif prog in _GUI_PROGS: # launch detached, poll briefly to catch early death
1315
+ proc = subprocess.Popen(argv, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
1316
+ try:
1317
+ proc.wait(timeout=1.5) # exited already → probably an error
1318
+ if proc.returncode:
1319
+ err = proc.stderr.read().decode(errors='replace').strip()
1320
+ hint = ' (try: xhost +local:)' if 'Authorization' in err else ''
1321
+ fail_msg = f'{prog} failed ({proc.returncode}): {err[:120]}{hint}'
1322
+ self._set_summary(as_plain(fail_msg, Sty.ERR))
1323
+ return
1324
+ except subprocess.TimeoutExpired:
1325
+ pass # still running → GUI opened fine
1326
+ self._set_summary(as_plain(f'Opened in {prog}', Sty.OK))
1327
+
1328
+ else: # CLI tools: capture output and show in scrollable dialog
1329
+ if prog == 'diff': # optimise output
1330
+ content = builtin_diff(left, right)
1331
+ else:
1332
+ r = subprocess.run(argv, capture_output=True, text=True, timeout=30)
1333
+ content = r.stdout or r.stderr or '(no output)'
1334
+ self.push_screen(DiffOutputScreen(content, left, right))
1335
+
1336
+ except FileNotFoundError:
1337
+ self._set_summary(fmt('command not found: {}', argv[0], Sty.ERR))
1338
+ except subprocess.TimeoutExpired:
1339
+ self._set_summary(fmt('{} timed out (30s)', prog, Sty.WARN))
1340
+ except OSError as exc:
1341
+ self._set_summary(fmt('launch failed: {}', exc, Sty.ERR))
1342
+
1343
+ # ── resolve (overwrite one side or keep both) ──────────────────────────────────────
1344
+ def action_resolve_left(self) -> None:
1345
+ """Keep LEFT version — overwrite right with left."""
1346
+ self._request_resolve(Side.LEFT)
1347
+
1348
+ def action_resolve_right(self) -> None:
1349
+ """Keep RIGHT version — overwrite left with right."""
1350
+ self._request_resolve(Side.RIGHT)
1351
+
1352
+ def _actionable(self, entries: list[FileEntry], *sides: Side) -> tuple[list[FileEntry], int]:
1353
+ """Split *entries* into those we can safely mutate on *sides*, and a refused count.
1354
+
1355
+ A missing side (kind None) is fine — that is what ``c`` creates. A FIFO,
1356
+ a device node or an unreadable entry is not something we copy or overwrite.
1357
+ """
1358
+ usable, refused = [], 0
1359
+ for e in entries:
1360
+ kinds = [e.side_kind(s) for s in sides]
1361
+ if all(k is None or k in _ACTIONABLE_KINDS for k in kinds):
1362
+ usable.append(e)
1363
+ else:
1364
+ refused += 1
1365
+ return usable, refused
1366
+
1367
+ def _warn_refused(self, refused: int, what: str) -> None:
1368
+ if refused:
1369
+ self._set_summary(styled(f'{refused} non-regular file(s) cannot be {what}', Sty.WARN))
1370
+
1371
+ def _request_resolve(self, keep: Side) -> None:
1372
+ """Overwrite the other side with *keep* side's version."""
1373
+ if self._guard_dry_run('resolve'):
1374
+ return
1375
+ lose = keep.other
1376
+ targets, refused = self._actionable(self._get_action_target_entries(), keep, lose)
1377
+ resolvable: list[tuple[FileEntry, Path, Path]] = []
1378
+ for e in targets:
1379
+ if e.status != FileStatus.DIFFERENT:
1380
+ continue
1381
+ src, dst = e.side_path(keep), e.side_path(lose)
1382
+ if src and dst:
1383
+ resolvable.append((e, src, dst))
1384
+ if not resolvable:
1385
+ self._warn_refused(refused, 'resolved')
1386
+ return
1387
+ paths = self._format_transfers(resolvable)
1388
+ title = f'Keep {styled(keep.label, Sty.ACCENT)}, overwrite {lose.label} ({len(paths)} file(s))?'
1389
+ entries = [e for e, _, _ in resolvable]
1390
+ detail = '\n'.join(overwrite_warning(lose) + self._selection_notes(entries, refused))
1391
+ total = self._sum_sizes(e.side_size(keep) for e, _, _ in resolvable)
1392
+ self.push_screen(ConfirmScreen(title, detail, action='Overwrite',
1393
+ paths=paths, total_bytes=total),
1394
+ callback=lambda ok: ok and self._do_resolve(resolvable, keep))
1395
+
1396
+ def _do_resolve(self, items: list[tuple[FileEntry, Path, Path]], keep: Side) -> None:
1397
+ lose = keep.other
1398
+ tasks = []
1399
+ for e, src, dst in items:
1400
+ kept_requirement = self._unchanged_since_scan(e, keep)
1401
+ lost_requirement = self._unchanged_since_scan(e, lose) # the file about to be overwritten
1402
+ tasks.append(BatchTask(
1403
+ entry=e, checks=(kept_requirement, lost_requirement),
1404
+ execute=partial(self._file_ops.copy, src, dst, verify_hash=self._algo,
1405
+ follow_symlinks=self._deref, replacing=lost_requirement),
1406
+ on_success=partial(self._resolve_on_success, e, keep),
1407
+ label=src.name,
1408
+ ))
1409
+ self._start_batch(tasks, f'Resolving → {keep.label}', f'resolved → {keep.label}')
1410
+
1411
+ def action_keep_both(self) -> None:
1412
+ """Park conflicts: tag both names (--tag-left / --tag-right), copy both to both sides."""
1413
+ if self._guard_dry_run('keep-both'):
1414
+ return
1415
+ targets = self._get_action_target_entries()
1416
+ targets, refused = self._actionable(targets, Side.LEFT, Side.RIGHT)
1417
+ resolvable = [(e, e.left_path, e.right_path)
1418
+ for e in targets if e.status == FileStatus.DIFFERENT and e.left_path and e.right_path]
1419
+ if not resolvable:
1420
+ self._warn_refused(refused, 'parked')
1421
+ return
1422
+ preview = []
1423
+ for e, src, dst in resolvable:
1424
+ left_name = tagged_name(src, self._tag_left).name
1425
+ right_name = tagged_name(dst, self._tag_right).name
1426
+ preview.append(f'{e.rel_path} → {left_name} + {right_name}')
1427
+ total = 2 * self._sum_sizes((e.side_size(Side.LEFT) or 0) + (e.side_size(Side.RIGHT) or 0)
1428
+ for e, _, _ in resolvable)
1429
+ self.push_screen(ConfirmScreen(f'Keep both versions for {len(resolvable)} file(s)?',
1430
+ 'Renames originals and cross-copies so both sides match.',
1431
+ action='Keep Both', paths=preview, total_bytes=total),
1432
+ callback=lambda ok: ok and self._do_keep_both(resolvable))
1433
+
1434
+ def _do_keep_both(self, items: list[tuple[FileEntry, Path, Path]]) -> None:
1435
+ tasks = []
1436
+ for e, src, dst in items:
1437
+ l_tag = tagged_name(src, self._tag_left)
1438
+ r_tag = tagged_name(dst, self._tag_right)
1439
+ tasks.append(BatchTask(
1440
+ entry=e,
1441
+ checks=(self._unchanged_since_scan(e, Side.LEFT),
1442
+ self._unchanged_since_scan(e, Side.RIGHT),
1443
+ MutationRequirement.absent(l_tag), MutationRequirement.absent(r_tag),
1444
+ MutationRequirement.absent(dst.parent / l_tag.name),
1445
+ MutationRequirement.absent(src.parent / r_tag.name)),
1446
+ execute=partial(self._file_ops.keep_both, src, dst, verify_hash=self._algo,
1447
+ tags=(self._tag_left, self._tag_right),
1448
+ follow_symlinks=self._deref),
1449
+ on_success=partial(self._keep_both_on_success, e, l_tag.name, r_tag.name),
1450
+ label=e.rel_path,
1451
+ ))
1452
+ self._start_batch(tasks, 'Keeping both', 'parked')