ddiff-tui 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ddiff/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """ddiff: see what changed between two data files."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("ddiff-tui")
7
+ except PackageNotFoundError: # running from a source tree that isn't installed
8
+ __version__ = "0.0.0"
ddiff/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .app import main
2
+
3
+ main()
ddiff/app.py ADDED
@@ -0,0 +1,658 @@
1
+ """ddiff: what changed between two data files, in your terminal.
2
+
3
+ ddiff old.parquet new.parquet # explore the differences
4
+ ddiff old.csv new.csv -k id # match rows on id
5
+ ddiff a.parquet b.parquet --summary # print a summary; exit 1 if they differ
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+
16
+ from rich.console import Console
17
+ from rich.text import Text
18
+ from textual import on, work
19
+ from textual.app import App, ComposeResult
20
+ from textual.binding import Binding
21
+ from textual.containers import Horizontal, VerticalScroll
22
+ from textual.widgets import Footer, Input, Static, TabbedContent, TabPane
23
+
24
+ from . import __version__
25
+ from .engine import STATUSES, Col, Diff, DiffError, Options, View
26
+ from .grid import Grid
27
+ from .screens import ColumnScreen, HelpScreen, PromptScreen, RowScreen, TextScreen
28
+ from .views import ColumnsSource, RowsSource, summary
29
+
30
+ TAB_FOCUS = {"tab-summary": "#summary-scroll", "tab-columns": "#cols", "tab-rows": "#rows"}
31
+
32
+
33
+ class DiffApp(App):
34
+ TITLE = "ddiff"
35
+ CSS = """
36
+ Screen { layout: vertical; }
37
+ #status { height: 1; background: $panel; color: $text; padding: 0 1; }
38
+ #status #files { width: 1fr; }
39
+ #status #pos { width: auto; color: $text-muted; }
40
+ TabbedContent { height: 1fr; }
41
+ TabPane { padding: 0; }
42
+ #summary { padding: 1 2; }
43
+ #filterbar { height: 1; background: $panel; padding: 0 1; }
44
+ #cols-filter { dock: top; background: $panel; margin-bottom: 1; }
45
+ """
46
+
47
+ BINDINGS = [
48
+ Binding("q", "quit", "Quit"),
49
+ Binding("1", "tab('tab-summary')", "Summary", show=False),
50
+ Binding("2", "tab('tab-columns')", "Columns", show=False),
51
+ Binding("3", "tab('tab-rows')", "Rows", show=False),
52
+ Binding("c", "column", "Column"),
53
+ Binding("f", "filter_column", "Only this column"),
54
+ Binding("d", "sort_delta", "Biggest Δ"),
55
+ Binding("a,plus", "toggle_status('added')", "Added", show=False),
56
+ Binding("r,minus", "toggle_status('removed')", "Removed", show=False),
57
+ Binding("m,tilde", "toggle_status('changed')", "Modified", show=False),
58
+ Binding("u", "toggle_unchanged", "Unchanged cols", show=False),
59
+ Binding("x", "clear", "Clear", show=False),
60
+ Binding("slash", "find_column", "Find column", show=False),
61
+ Binding("w", "save", "Save"),
62
+ Binding("D", "open_dx", "dx", show=False),
63
+ Binding("S", "sql", "SQL"),
64
+ Binding("question_mark", "help", "Help"),
65
+ ]
66
+
67
+ def __init__(self, old: str, new: str, options: Options | None = None):
68
+ super().__init__()
69
+ self.old, self.new, self.options = old, new, options or Options()
70
+ self.diff: Diff | None = None
71
+ self.view: View | None = None
72
+ self.statuses = frozenset(STATUSES)
73
+ self.col_filter: int | None = None
74
+ self.sort: tuple | None = None # (item, asc, delta)
75
+ self.show_unchanged = False
76
+ self.busy = True
77
+ self.failed = False
78
+ self._pending = False # a filter / sort changed while a view was being built
79
+ self.col_order: list[Col] = []
80
+ self.col_sort: tuple[int, bool] | None = None
81
+
82
+ @property
83
+ def loaded(self) -> bool:
84
+ """The diff is there (a view may still be building: filters and sorts queue up)."""
85
+ return self.diff is not None and self.view is not None
86
+
87
+ @property
88
+ def ready(self) -> bool:
89
+ return self.diff is not None and self.view is not None and not self.busy
90
+
91
+ # ------------------------------------------------------------- layout
92
+
93
+ def compose(self) -> ComposeResult:
94
+ with Horizontal(id="status"):
95
+ yield Static(
96
+ f"ddiff · {os.path.basename(self.old)} → {os.path.basename(self.new)}", id="files", markup=False
97
+ )
98
+ yield Static("", id="pos", markup=False)
99
+ with TabbedContent(initial="tab-summary"):
100
+ with TabPane("Summary [dim]1[/]", id="tab-summary"):
101
+ with VerticalScroll(id="summary-scroll"):
102
+ yield Static("", id="summary")
103
+ with TabPane("Columns [dim]2[/]", id="tab-columns"):
104
+ yield Input(
105
+ placeholder="filter columns by name… (Enter: details · s: sort · f: show its rows)",
106
+ id="cols-filter",
107
+ compact=True,
108
+ )
109
+ yield Grid(id="cols")
110
+ with TabPane("Rows [dim]3[/]", id="tab-rows"):
111
+ yield Static("", id="filterbar")
112
+ yield Grid(id="rows")
113
+ yield Footer()
114
+
115
+ def on_mount(self) -> None:
116
+ self.query_one(TabbedContent).loading = True
117
+ self._compute()
118
+
119
+ def on_unmount(self) -> None:
120
+ if self.diff is not None:
121
+ self.diff.close()
122
+
123
+ # ----------------------------------------------------------- computing
124
+
125
+ @work(thread=True, exclusive=True, group="diff")
126
+ def _compute(self) -> None:
127
+ diff = None
128
+ try:
129
+ diff = Diff(
130
+ self.old, self.new, self.options, progress=lambda msg: self.call_from_thread(self._progress, msg)
131
+ )
132
+ diff.run()
133
+ except Exception as e: # noqa: BLE001
134
+ if diff is not None:
135
+ diff.close()
136
+ msg = str(e) if isinstance(e, DiffError) else f"{type(e).__name__}: {e}"
137
+ self.call_from_thread(self._failed, msg)
138
+ return
139
+ self.call_from_thread(self._diff_ready, diff)
140
+ try:
141
+ diff.column_stats()
142
+ except Exception as e: # noqa: BLE001
143
+ self.call_from_thread(self.notify, f"Couldn't compute column stats: {e}", severity="warning", markup=False)
144
+ return
145
+ self.call_from_thread(self._stats_ready)
146
+
147
+ def _progress(self, msg: str) -> None:
148
+ self.query_one("#pos", Static).update(msg)
149
+
150
+ def _failed(self, msg: str) -> None:
151
+ self.busy = False
152
+ self.failed = True
153
+ self.query_one(TabbedContent).loading = False
154
+ self.query_one("#summary", Static).update(Text(f"Couldn't compare the files:\n\n{msg}", style="red"))
155
+ self.query_one("#pos", Static).update("failed")
156
+
157
+ def _diff_ready(self, diff: Diff) -> None:
158
+ d = self.diff = diff
159
+ self.busy = False
160
+ self.query_one(TabbedContent).loading = False
161
+ how = "by row position" if d.positional else f"on {', '.join(d.keys)}"
162
+ self.query_one("#files", Static).update(
163
+ Text.assemble("ddiff · ", (d.a.name, "red"), " → ", (d.b.name, "green"), f" · {how}")
164
+ )
165
+ self.query_one("#summary", Static).update(summary(d))
166
+ self.col_order = list(d.cols)
167
+ self._set_cols()
168
+ self.view = d.base
169
+ self._set_rows()
170
+ self._focus_tab()
171
+ self._update_pos()
172
+
173
+ def _stats_ready(self) -> None:
174
+ self.query_one("#cols", Grid).refresh_cells()
175
+ if self.col_sort:
176
+ self._sort_cols(*self.col_sort)
177
+
178
+ # ------------------------------------------------------------- Columns
179
+
180
+ def _set_cols(self, keep: bool = False) -> None:
181
+ text = self.query_one("#cols-filter", Input).value.strip().lower()
182
+ cols = [c for c in self.col_order if text in c.name.lower()] if text else self.col_order
183
+ self.query_one("#cols", Grid).set_source(ColumnsSource(self.diff, cols), keep_position=keep)
184
+
185
+ @on(Input.Changed, "#cols-filter")
186
+ def _cols_filter(self) -> None:
187
+ if self.diff:
188
+ self._set_cols()
189
+
190
+ @on(Input.Submitted, "#cols-filter")
191
+ def _cols_filter_done(self) -> None:
192
+ self.query_one("#cols", Grid).focus()
193
+
194
+ def _sort_cols(self, i: int, asc: bool) -> None:
195
+ src = ColumnsSource(self.diff, self.diff.cols)
196
+
197
+ def key(c):
198
+ v = src.value(c, i)
199
+ return (v is None, v if v is not None else 0) if not isinstance(v, str) else (False, v)
200
+
201
+ try:
202
+ ordered = sorted(self.diff.cols, key=key, reverse=not asc)
203
+ except TypeError: # mixed types (e.g. min of text and numbers): compare as text
204
+ ordered = sorted(self.diff.cols, key=lambda c: str(src.value(c, i)), reverse=not asc)
205
+ if not asc: # keep missing values last
206
+ ordered = [c for c in ordered if src.value(c, i) is not None] + [
207
+ c for c in ordered if src.value(c, i) is None
208
+ ]
209
+ self.col_order = ordered
210
+ self._set_cols(keep=True)
211
+ self.query_one("#cols", Grid).show_sort(i, asc)
212
+
213
+ def _cursor_col(self) -> Col | None:
214
+ """The diff column under the cursor (Rows or Columns tab)."""
215
+ tab = self.query_one(TabbedContent).active
216
+ if tab == "tab-columns":
217
+ g = self.query_one("#cols", Grid)
218
+ if g.source and g.nrows:
219
+ return g.source.cols[g.cursor_row]
220
+ elif tab == "tab-rows":
221
+ g = self.query_one("#rows", Grid)
222
+ if g.source:
223
+ it = g.source.item(g.cursor_col)
224
+ return it if isinstance(it, Col) else None
225
+ return None
226
+
227
+ # ---------------------------------------------------------------- Rows
228
+
229
+ def _set_rows(self, keep: bool = False) -> None:
230
+ grid = self.query_one("#rows", Grid)
231
+ grid.set_source(RowsSource(self.diff, self.view, self.show_unchanged), keep_position=keep)
232
+ if self.sort:
233
+ item, asc, delta = self.sort
234
+ items = grid.source.items
235
+ grid.show_sort(items.index(item) if item in items else None, asc, "Δ" if delta else None)
236
+ else:
237
+ grid.show_sort(None)
238
+ self._update_filterbar()
239
+
240
+ def _rebuild_view(self) -> None:
241
+ d = self.diff
242
+ if d is None or self.view is None:
243
+ return
244
+ if self.busy:
245
+ self._pending = True
246
+ return
247
+ order = None
248
+ if self.sort:
249
+ item, asc, delta = self.sort
250
+ order = d.sort_sql(item, asc, delta)
251
+ self.busy = True
252
+ self.query_one("#rows", Grid).loading = True
253
+ self._make_view(self.statuses, self.col_filter, order)
254
+
255
+ @work(thread=True, exclusive=True, group="view")
256
+ def _make_view(self, statuses, column, order) -> None:
257
+ try:
258
+ view = self.diff.make_view(statuses, column, order)
259
+ except Exception as e: # noqa: BLE001
260
+ self.call_from_thread(self._view_failed, str(e))
261
+ return
262
+ self.call_from_thread(self._view_ready, view)
263
+
264
+ def _view_failed(self, msg: str) -> None:
265
+ self.busy = False
266
+ self._pending = False
267
+ self.query_one("#rows", Grid).loading = False
268
+ self.notify(msg, severity="error", markup=False)
269
+
270
+ def _view_ready(self, view: View) -> None:
271
+ self.busy = False
272
+ old, self.view = self.view, view
273
+ if old is not view:
274
+ self.diff.drop_view(old)
275
+ grid = self.query_one("#rows", Grid)
276
+ grid.loading = False
277
+ self._set_rows(keep=True)
278
+ grid.move_to(row=0)
279
+ grid.focus()
280
+ self._update_pos()
281
+ if self._pending:
282
+ self._pending = False
283
+ self._rebuild_view()
284
+
285
+ def _update_filterbar(self) -> None:
286
+ d = self.diff
287
+ t = Text()
288
+ t.append(f"{self.view.nrows:,} rows", style="bold")
289
+ t.append(" of ", style="dim")
290
+ t.append(f"{d.n_diff:,} differing ")
291
+ for st, label, sym, style in (
292
+ ("added", "added", "+", "green"),
293
+ ("removed", "removed", "−", "red"),
294
+ ("changed", "modified", "~", "yellow"),
295
+ ):
296
+ on_ = st in self.statuses
297
+ t.append(f" {sym} {label} {d.counts[st]:,} ", style=f"bold {style}" if on_ else "dim strike")
298
+ if self.col_filter is not None:
299
+ t.append(" · only where ", style="dim")
300
+ t.append(d.compared(self.col_filter).name, style="bold yellow")
301
+ t.append(" changed", style="dim")
302
+ if self.sort:
303
+ item, asc, delta = self.sort
304
+ name = item if isinstance(item, str) else item.name
305
+ t.append(" · sorted by ", style="dim")
306
+ t.append(("|Δ| " if delta else "") + name + (" ↑" if asc else " ↓"), style="bold")
307
+ hidden = sum(1 for c in d.cols if c.kind == "compared" and not c.changed)
308
+ if hidden and not self.show_unchanged:
309
+ t.append(f" · {hidden:,} unchanged columns hidden (u)", style="dim")
310
+ self.query_one("#filterbar", Static).update(t)
311
+
312
+ # ------------------------------------------------------------- events
313
+
314
+ @on(Grid.CursorMoved)
315
+ def _moved(self) -> None:
316
+ self._update_pos()
317
+
318
+ @on(TabbedContent.TabActivated)
319
+ def _tab_changed(self) -> None:
320
+ self._focus_tab()
321
+ self._update_pos()
322
+
323
+ def _focus_tab(self) -> None:
324
+ tab = self.query_one(TabbedContent).active
325
+ if tab in TAB_FOCUS:
326
+ self.query_one(TAB_FOCUS[tab]).focus()
327
+
328
+ def _update_pos(self) -> None:
329
+ if not self.ready:
330
+ return
331
+ tab = self.query_one(TabbedContent).active
332
+ text = ""
333
+ if tab == "tab-rows":
334
+ g = self.query_one("#rows", Grid)
335
+ if g.nrows:
336
+ text = f"row {g.cursor_row + 1:,} of {g.nrows:,} · column {g.cursor_col + 1:,} of {g.ncols:,}"
337
+ else:
338
+ text = "no rows to show"
339
+ elif tab == "tab-columns":
340
+ g = self.query_one("#cols", Grid)
341
+ text = f"column {g.cursor_row + 1:,} of {g.nrows:,}" if g.nrows else "no columns match"
342
+ self.query_one("#pos", Static).update(text)
343
+
344
+ @on(Grid.Selected, "#rows")
345
+ def _row_selected(self, event: Grid.Selected) -> None:
346
+ self.push_screen(RowScreen(self.diff, self.view, event.row))
347
+
348
+ @on(Grid.Selected, "#cols")
349
+ def _col_selected(self) -> None:
350
+ self.action_column()
351
+
352
+ @on(Grid.SortRequested, "#rows")
353
+ def _sort_rows(self, event: Grid.SortRequested) -> None:
354
+ item = event.grid.source.item(event.col)
355
+ if self.sort and self.sort[0] == item and not self.sort[2]:
356
+ self.sort = (item, False, False) if self.sort[1] else None
357
+ else:
358
+ self.sort = (item, True, False)
359
+ self._rebuild_view()
360
+
361
+ @on(Grid.SortRequested, "#cols")
362
+ def _sort_cols_requested(self, event: Grid.SortRequested) -> None:
363
+ if self.col_sort and self.col_sort[0] == event.col:
364
+ if self.col_sort[1]:
365
+ self.col_sort = (event.col, False)
366
+ else:
367
+ self.col_sort = None
368
+ self.col_order = list(self.diff.cols)
369
+ self._set_cols(keep=True)
370
+ event.grid.show_sort(None)
371
+ return
372
+ else:
373
+ self.col_sort = (event.col, event.col in (0, 2)) # names ascending, numbers biggest first
374
+ self._sort_cols(*self.col_sort)
375
+
376
+ # ------------------------------------------------------------- actions
377
+
378
+ def action_tab(self, tab: str) -> None:
379
+ self.query_one(TabbedContent).active = tab
380
+ self._focus_tab()
381
+
382
+ def _after_dialog(self, tab: str, then, *args) -> None:
383
+ """Switch to ``tab`` once a dialog has closed, then run ``then(*args)``.
384
+
385
+ TabbedContent follows focus, and when a dialog closes the main screen re-focuses
386
+ whatever it had focused before, pulling that tab back to the front. So the main
387
+ screen's focus moves to the new tab's widget first (the dialog may still be on top,
388
+ so query the main screen, not the active one)."""
389
+ main = self.screen_stack[0]
390
+ main.set_focus(main.query_one(TAB_FOCUS[tab]))
391
+ self.call_after_refresh(then, *args)
392
+
393
+ def action_column(self) -> None:
394
+ if not self.ready:
395
+ return
396
+ col = self._cursor_col()
397
+ if col is None:
398
+ self.notify("Put the cursor on a column first", severity="warning")
399
+ return
400
+
401
+ def done(result):
402
+ if result == "filter":
403
+ self._after_dialog("tab-rows", self._filter_on, col)
404
+
405
+ self.push_screen(ColumnScreen(self.diff, col), done)
406
+
407
+ def _filter_on(self, col: Col) -> None:
408
+ self.col_filter = col.index
409
+ self.action_tab("tab-rows")
410
+ self._rebuild_view()
411
+
412
+ def action_filter_column(self) -> None:
413
+ if not self.loaded:
414
+ return
415
+ if self.col_filter is not None and self.query_one(TabbedContent).active == "tab-rows":
416
+ self.col_filter = None
417
+ self._rebuild_view()
418
+ return
419
+ col = self._cursor_col()
420
+ if col is None or col.kind != "compared" or not col.changed:
421
+ self.notify("No values changed in this column", severity="warning")
422
+ return
423
+ self._filter_on(col)
424
+
425
+ def action_sort_delta(self) -> None:
426
+ if not self.loaded or self.query_one(TabbedContent).active != "tab-rows":
427
+ return
428
+ col = self._cursor_col()
429
+ if col is None or col.kind != "compared" or not col.numeric:
430
+ self.notify("Sorting by the size of a change needs a numeric column", severity="warning")
431
+ return
432
+ if self.sort and self.sort[0] is col and self.sort[2]:
433
+ self.sort = None
434
+ else:
435
+ self.sort = (col, False, True)
436
+ self._rebuild_view()
437
+
438
+ def action_toggle_status(self, status: str) -> None:
439
+ if not self.loaded:
440
+ return
441
+ self.statuses = self.statuses ^ {status}
442
+ self.action_tab("tab-rows")
443
+ self._rebuild_view()
444
+
445
+ def action_toggle_unchanged(self) -> None:
446
+ if not self.ready:
447
+ return
448
+ self.show_unchanged = not self.show_unchanged
449
+ self._set_rows(keep=True)
450
+
451
+ def action_clear(self) -> None:
452
+ if not self.loaded:
453
+ return
454
+ self.statuses, self.col_filter, self.sort = frozenset(STATUSES), None, None
455
+ self._rebuild_view()
456
+
457
+ def action_find_column(self) -> None:
458
+ if not self.ready:
459
+ return
460
+ tab = self.query_one(TabbedContent).active
461
+ if tab == "tab-columns":
462
+ self.query_one("#cols-filter", Input).focus()
463
+ return
464
+
465
+ def done(text):
466
+ if text:
467
+ self._after_dialog("tab-rows", self._find_column, text)
468
+
469
+ self.push_screen(PromptScreen("Find a column", placeholder="name or part of one"), done)
470
+
471
+ def _find_column(self, text: str) -> None:
472
+ self.action_tab("tab-rows")
473
+ g = self.query_one("#rows", Grid)
474
+ names = [c.name.lower() for c in g.source.columns]
475
+ t = text.lower()
476
+ hits = [i for i, n in enumerate(names) if n == t] or [i for i, n in enumerate(names) if t in n]
477
+ if hits:
478
+ g.move_to(col=hits[0])
479
+ return
480
+ hidden = [c for c in self.diff.cols if t in c.name.lower()]
481
+ if hidden and not self.show_unchanged:
482
+ self.show_unchanged = True
483
+ self._set_rows(keep=True)
484
+ self._find_column(text)
485
+ else:
486
+ self.notify(f"No column matches {text!r}", severity="warning", markup=False)
487
+
488
+ def action_save(self) -> None:
489
+ if not self.ready:
490
+ return
491
+
492
+ def done(path):
493
+ if path:
494
+ self._save(path, self.view)
495
+
496
+ self.push_screen(
497
+ PromptScreen(
498
+ f"Save the {self.view.nrows:,} rows on show",
499
+ "ddiff.parquet",
500
+ hint="parquet, csv, tsv, json, jsonl or xlsx. Columns: status, key, row_old, row_new, then "
501
+ "<column>_old and <column>_new for every changed column.",
502
+ ),
503
+ done,
504
+ )
505
+
506
+ @work(thread=True, group="save")
507
+ def _save(self, path: str, view: View) -> None:
508
+ try:
509
+ n = self.diff.save(path, view)
510
+ except Exception as e: # noqa: BLE001
511
+ self.call_from_thread(self.notify, f"Couldn't save: {e}", severity="error", markup=False)
512
+ return
513
+ self.call_from_thread(self.notify, f"Saved {n:,} rows to {path}", markup=False)
514
+
515
+ def action_open_dx(self) -> None:
516
+ if not self.ready:
517
+ return
518
+ dx = shutil.which("dx")
519
+ if dx is None:
520
+ self.notify(
521
+ "dx isn't installed: uv tool install git+https://github.com/jimhendy/dx",
522
+ severity="warning",
523
+ markup=False,
524
+ timeout=8,
525
+ )
526
+ return
527
+ path = os.path.join(self.diff._dir, "view.parquet")
528
+ try:
529
+ self.diff.save(path, self.view)
530
+ except Exception as e: # noqa: BLE001
531
+ self.notify(f"Couldn't export the rows: {e}", severity="error", markup=False)
532
+ return
533
+ with self.suspend():
534
+ subprocess.run([dx, path, "-y"], check=False)
535
+
536
+ def action_sql(self) -> None:
537
+ if not self.ready:
538
+ return
539
+ self.push_screen(TextScreen("The SQL behind this diff (DuckDB)", self.diff.sql_script()))
540
+
541
+ def action_help(self) -> None:
542
+ self.push_screen(HelpScreen())
543
+
544
+
545
+ # ---------------------------------------------------------------------------
546
+ # CLI
547
+ # ---------------------------------------------------------------------------
548
+
549
+
550
+ def _names(values: list[str] | None) -> list[str] | None:
551
+ if not values:
552
+ return None
553
+ out = []
554
+ for v in values:
555
+ out += [n.strip() for n in v.split(",") if n.strip()]
556
+ return out
557
+
558
+
559
+ def parser() -> argparse.ArgumentParser:
560
+ p = argparse.ArgumentParser(
561
+ prog="ddiff",
562
+ description="See what changed between two data files: parquet, CSV, TSV, JSON, JSON lines, Excel, "
563
+ "Arrow. Any size: DuckDB does the comparing.",
564
+ formatter_class=argparse.RawDescriptionHelpFormatter,
565
+ epilog="""examples:
566
+ ddiff old.parquet new.parquet explore the differences
567
+ ddiff old.csv new.csv -k id match rows on the id column
568
+ ddiff a.parquet b.parquet -k date,ticker a key of two columns
569
+ ddiff a.xlsx::Sheet1 b.xlsx::Sheet1 Excel sheets
570
+ ddiff a.parquet b.parquet --atol 1e-9 numbers this close are equal
571
+ ddiff a.parquet b.parquet -w "region = 'EU'"
572
+ ddiff a.parquet b.parquet --summary print a summary (exit 0 same, 1 different, 2 error)
573
+ ddiff a.parquet b.parquet -o diff.parquet save the differences and exit
574
+ """,
575
+ )
576
+ p.add_argument("old", help="the old file (FILE::SHEET for an Excel sheet)")
577
+ p.add_argument("new", help="the new file")
578
+ p.add_argument(
579
+ "-k",
580
+ "--key",
581
+ action="append",
582
+ metavar="COLS",
583
+ help="column(s) that identify a row, comma separated (default: a column unique in both "
584
+ "files, else row position)",
585
+ )
586
+ p.add_argument("-c", "--columns", action="append", metavar="COLS", help="compare only these columns")
587
+ p.add_argument("-i", "--ignore", action="append", metavar="COLS", help="don't compare these columns")
588
+ p.add_argument("-w", "--where", metavar="SQL", help="compare only rows matching this SQL filter (both files)")
589
+ p.add_argument("--atol", type=float, default=0.0, help="absolute tolerance for numbers")
590
+ p.add_argument("--rtol", type=float, default=0.0, help="relative tolerance for numbers")
591
+ p.add_argument("-s", "--summary", action="store_true", help="print a summary instead of opening the app")
592
+ p.add_argument("--json", action="store_true", help="print the summary as JSON")
593
+ p.add_argument("-o", "--output", metavar="FILE", help="save the differing rows to FILE and exit")
594
+ p.add_argument("--tmp", metavar="DIR", help="where to keep the working database (default: system temp)")
595
+ p.add_argument("-V", "--version", action="version", version=f"ddiff {__version__}")
596
+ return p
597
+
598
+
599
+ def options_from(args) -> Options:
600
+ return Options(
601
+ key=_names(args.key),
602
+ columns=_names(args.columns),
603
+ ignore=_names(args.ignore) or [],
604
+ where=args.where,
605
+ atol=args.atol,
606
+ rtol=args.rtol,
607
+ tmp_dir=args.tmp,
608
+ )
609
+
610
+
611
+ def _safe_streams() -> None:
612
+ """Never crash printing →, ✓, █… to a stream that can't encode them (a Windows pipe is cp1252)."""
613
+ for stream in (sys.stdout, sys.stderr):
614
+ encoding = (getattr(stream, "encoding", None) or "").lower().replace("-", "")
615
+ if encoding != "utf8" and hasattr(stream, "reconfigure"):
616
+ stream.reconfigure(errors="replace")
617
+
618
+
619
+ def main(argv: list[str] | None = None) -> int:
620
+ args = parser().parse_args(argv)
621
+ opts = options_from(args)
622
+ if args.summary or args.json or args.output:
623
+ _safe_streams()
624
+ err = Console(stderr=True)
625
+ try:
626
+ progress = (
627
+ (lambda m: None)
628
+ if args.json or not sys.stderr.isatty()
629
+ else (lambda m: err.print(Text(m, style="dim")))
630
+ )
631
+ with Diff(args.old, args.new, opts, progress=progress) as d:
632
+ d.run()
633
+ if args.output:
634
+ n = d.save(args.output)
635
+ err.print(Text(f"Saved {n:,} differing rows to {args.output}"))
636
+ if args.json:
637
+ import json
638
+
639
+ print(json.dumps(d.to_dict(), indent=2))
640
+ elif args.summary:
641
+ Console().print(summary(d))
642
+ code = 0 if d.identical else 1
643
+ except DiffError as e:
644
+ err.print(Text(f"ddiff: {e}", style="red"))
645
+ code = 2
646
+ sys.exit(code)
647
+ for path in (args.old, args.new):
648
+ from .engine import split_spec
649
+
650
+ if not os.path.isfile(split_spec(path)[0]):
651
+ print(f"ddiff: no such file: {path}", file=sys.stderr)
652
+ sys.exit(2)
653
+ DiffApp(args.old, args.new, opts).run()
654
+ return 0
655
+
656
+
657
+ if __name__ == "__main__":
658
+ main()