Skip to content

Instantly share code, notes, and snippets.

@panzi
Last active November 17, 2026 21:51
Show Gist options
  • Select an option

  • Save panzi/0d92b2fada489dc9f7f184742e5e7d38 to your computer and use it in GitHub Desktop.

Select an option

Save panzi/0d92b2fada489dc9f7f184742e5e7d38 to your computer and use it in GitHub Desktop.
Very simple table diffing in Python. NOTE: It compares cell contents a little bit fuzzy per default.
#!/usr/bin/env python3
from typing import Sequence, NamedTuple, Callable, Literal, Match
from enum import Enum
from html import escape as h
from io import StringIO
from os.path import splitext
from unicodedata import normalize
import re
import csv
wcswidth: Callable[[str], int]
try:
from uwcwidth import wcswidth # type: ignore
except ImportError:
try:
from wcwidth import wcswidth # type: ignore
except ImportError:
try:
from cwcwidth import wcswidth # type: ignore
except ImportError:
wcswidth = len
__all__ = 'diff_table', 'diff_tables',
class Side(Enum):
Left = -1
Right = +1
class CompareStrategy(Enum):
Fuzzy = 'fuzzy'
Strict = 'strict'
DEFAULT_TABLE_WINDOW = 4
DEFAULT_ROW_WINDOW = 4
DEFAULT_COLUMN_WINDOW = 4
class TableCell(NamedTuple):
cell_index: int
content: str
fuzzy_content: str # case-folded, removed whitespace and more, see _fuzzy_text()
class TableRow(NamedTuple):
row_index: int
cells: list[TableCell]
class CellResult(NamedTuple):
lhs: TableCell|None
rhs: TableCell|None
class RowResultCell(NamedTuple):
cell: TableCell
matches: bool
class RowResult(NamedTuple):
cells: list[CellResult]
fail_count: int
lhs: list[RowResultCell]
rhs: list[RowResultCell]
lhs_index: int
rhs_index: int
STYLE = '''
.row-index {
text-align: right;
}
.left-only {
color: white;
background: red;
}
.right-only {
color: white;
background: green;
}
.side-by-side-gap {
width: 1em;
}
.table-diff td {
white-space: preserve;
}
'''
def style_tag() -> str:
return f'<style type="text/css">{h(STYLE)}</style>'
class TableResult(NamedTuple):
lhs: list[TableRow]
rhs: list[TableRow]
rows: list[RowResult]
cell_fails: int
cell_count: int
row_fails: int
row_count: int
lhs_index: int
rhs_index: int
def to_html(self, side_by_side: bool=False) -> str:
buf: list[str] = []
self._to_html(buf, side_by_side)
return ''.join(buf)
def _to_html(self, buf: list[str], side_by_side: bool) -> None:
lhs_columns = 0
rhs_columns = 0
for row in self.rows:
lhs_len = len(row.lhs)
rhs_len = len(row.rhs)
if lhs_len > lhs_columns:
lhs_columns = lhs_len
if rhs_len > rhs_columns:
rhs_columns = rhs_len
columns = max(lhs_columns, rhs_columns)
buf.append('<table class="table-diff">')
lhs_index = self.lhs_index
rhs_index = self.rhs_index
if lhs_index != -1 and rhs_index != -1:
buf.append(f'<caption>Table {lhs_index + 1} &lt;-&gt; Table {rhs_index + 1}</caption>\n')
elif lhs_index != -1:
buf.append(f'<caption>Left Table {lhs_index + 1}</caption>\n')
elif rhs_index != -1:
buf.append(f'<caption>Right Table {rhs_index + 1}</caption>\n')
if side_by_side:
buf.append('<thead><tr><th>Row</th>')
for col in range(1, lhs_columns + 1):
buf.append(f'<th>{col}</th>')
buf.append(f'<th class="side-by-side-gap"></th>')
buf.append('<th>Row</th>')
for col in range(1, rhs_columns + 1):
buf.append(f'<th>{col}</th>')
buf.append('</tr>\n</thead><tbody>\n')
for row in self.rows:
lhs_index = row.lhs_index
rhs_index = row.rhs_index
buf.append('<tr>')
if lhs_index == -1:
buf.append('<td class="row-index"></td>')
for _ in range(lhs_columns):
buf.append('<td></td>')
else:
if row.fail_count == 0:
buf.append(f'<td class="row-index">{lhs_index + 1}</td>')
else:
buf.append(f'<td class="row-index left-only">{lhs_index + 1}</td>')
for cell_res in row.lhs:
if cell_res.matches:
buf.append('<td>')
else:
buf.append('<td class="left-only">')
buf.append(h(cell_res.cell.content))
buf.append('</td>')
for _ in range(lhs_columns - len(row.lhs)):
buf.append('<td></td>')
buf.append('<td class="side-by-side-gap"></td>')
if rhs_index == -1:
buf.append('<td class="row-index"></td>')
for _ in range(rhs_columns):
buf.append('<td></td>')
else:
if row.fail_count == 0:
buf.append(f'<td class="row-index">{rhs_index + 1}</td>')
else:
buf.append(f'<td class="row-index right-only">{rhs_index + 1}</td>')
for cell_res in row.rhs:
if cell_res.matches:
buf.append('<td>')
else:
buf.append('<td class="right-only">')
buf.append(h(cell_res.cell.content))
buf.append('</td>')
for _ in range(rhs_columns - len(row.rhs)):
buf.append('<td></td>')
buf.append('</tr>\n')
else:
buf.append('<thead><tr><th colspan="2">Row</th>')
for col in range(1, columns + 1):
buf.append(f'<th>{col}</th>')
buf.append('</tr>\n</thead><tbody>\n')
for row in self.rows:
lhs_index = row.lhs_index
rhs_index = row.rhs_index
if row.fail_count == 0:
buf.append(f'<tr><td class="row-index">{lhs_index + 1}</td><td class="row-index">{rhs_index + 1}</td>')
for cell_res in row.rhs:
buf.append('<td>')
buf.append(h(cell_res.cell.content))
buf.append('</td>')
buf.append('</tr>\n')
else:
if lhs_index != -1:
buf.append(f'<tr><td class="row-index left-only">{lhs_index + 1}</td><td class="row-index"></td>')
for cell_res in row.lhs:
if cell_res.matches:
buf.append('<td rowspan="2">')
else:
buf.append('<td class="left-only">')
buf.append(h(cell_res.cell.content))
buf.append('</td>')
buf.append('</tr>\n')
if rhs_index != -1:
buf.append(f'<tr><td class="row-index"></td><td class="row-index right-only">{rhs_index + 1}</td>')
for cell_res in row.rhs:
if not cell_res.matches:
buf.append('<td class="right-only">')
buf.append(h(cell_res.cell.content))
buf.append('</td>')
buf.append('</tr>\n')
buf.append('</tbody></table>')
def to_ansi(self, side_by_side: bool=False) -> str:
buf: list[str] = []
self._to_ansi(buf, side_by_side)
return ''.join(buf)
def _to_ansi(self, buf: list[str], side_by_side: bool=False) -> None:
lhs_columns = 0
rhs_columns = 0
for row in self.rows:
lhs_len = len(row.lhs)
rhs_len = len(row.rhs)
if lhs_len > lhs_columns:
lhs_columns = lhs_len
if rhs_len > rhs_columns:
rhs_columns = rhs_len
columns = max(lhs_columns, rhs_columns)
lhs_index = self.lhs_index
rhs_index = self.rhs_index
if lhs_index != -1 and rhs_index != -1:
buf.append(f'{_BOLD}Table {lhs_index + 1} <-> Table {rhs_index + 1}{_RESET}\n')
elif lhs_index != -1:
buf.append(f'{_BOLD}Left Table {lhs_index + 1}{_RESET}\n')
elif rhs_index != -1:
buf.append(f'{_BOLD}Right Table {rhs_index + 1}{_RESET}\n')
header: list[tuple[str, Align, str]]
table: list[list[tuple[str, Align, str]]]
if side_by_side:
header = [('', 'r', 'Row')]
header.extend((_BOLD, 'c', str(col)) for col in range(1, lhs_columns + 1))
header.append(('', 'c', ''))
header.append(('', 'r', 'Row'))
header.extend((_BOLD, 'c', str(col)) for col in range(1, rhs_columns + 1))
table = [header]
for row in self.rows:
lhs_index = row.lhs_index
rhs_index = row.rhs_index
fmt_row: list[tuple[str, Align, str]] = []
table.append(fmt_row)
if lhs_index == -1:
fmt_row.append(('', 'r', ''))
for _ in range(lhs_columns):
fmt_row.append(('', 'l', ''))
else:
if row.fail_count == 0:
fmt_row.append(('', 'r', str(lhs_index + 1)))
else:
fmt_row.append((_LEFT_ONLY, 'r', str(lhs_index + 1)))
for cell_res in row.lhs:
if cell_res.matches:
fmt = ''
else:
fmt = _LEFT_ONLY
fmt_row.append((fmt, 'l', cell_res.cell.content))
for _ in range(lhs_columns - len(row.lhs)):
fmt_row.append(('', 'l', ''))
fmt_row.append(('', 'c', ''))
if rhs_index == -1:
fmt_row.append(('', 'r', ''))
for _ in range(rhs_columns):
fmt_row.append(('', 'l', ''))
else:
if row.fail_count == 0:
fmt_row.append(('', 'r', str(rhs_index + 1)))
else:
fmt_row.append((_RIGHT_ONLY, 'r', str(rhs_index + 1)))
for cell_res in row.rhs:
if cell_res.matches:
fmt = ''
else:
fmt = _RIGHT_ONLY
fmt_row.append((fmt, 'l', cell_res.cell.content))
for _ in range(rhs_columns - len(row.rhs)):
fmt_row.append(('', 'l', ''))
_format_table(table, buf)
else:
header = [('', 'r', ''), ('', 'r', '')]
header.extend((_BOLD, 'c', str(col)) for col in range(1, columns + 1))
table = [header]
for row in self.rows:
lhs_index = row.lhs_index
rhs_index = row.rhs_index
if row.fail_count == 0:
fmt_row = []
table.append(fmt_row)
fmt_row.append(('', 'r', str(lhs_index + 1)))
fmt_row.append(('', 'r', str(rhs_index + 1)))
fmt_row.extend(('', 'l', cell_res.cell.content) for cell_res in row.rhs)
else:
if lhs_index != -1:
fmt_row = []
table.append(fmt_row)
fmt_row.append((_LEFT_ONLY, 'r', str(lhs_index + 1)))
fmt_row.append(('', 'r', ''))
for cell_res in row.lhs:
if cell_res.matches:
fmt = ''
else:
fmt = _LEFT_ONLY
fmt_row.append((fmt, 'l', cell_res.cell.content))
if rhs_index != -1:
fmt_row = []
table.append(fmt_row)
fmt_row.append(('', 'r', ''))
fmt_row.append((_RIGHT_ONLY, 'r', str(rhs_index + 1)))
for cell_res in row.rhs:
if cell_res.matches:
fmt_row.append(('', 'l', ''))
else:
fmt_row.append((_RIGHT_ONLY, 'l', cell_res.cell.content))
_format_table(table, buf)
def to_diff(self) -> str:
buf: list[str] = []
self._to_diff(buf)
return ''.join(buf)
def _to_diff(self, buf: list[str]) -> None:
lhs_index = self.lhs_index
rhs_index = self.rhs_index
buf.append(f'--- lhs/table_{lhs_index + 1}.csv\n')
buf.append(f'+++ rhs/table_{rhs_index + 1}.csv\n')
line_ranges_index = len(buf)
buf.append('\n')
lhs_line_count = 0
rhs_line_count = 0
sio = StringIO()
csv_writer = csv.writer(sio)
def add_row(mode: Literal[' ', '+', '-'], row: list[str]) -> int:
sio.seek(0)
sio.truncate(0)
csv_writer.writerow(row)
str_row = sio.getvalue()
lines = str_row.splitlines(keepends=True)
for line in lines:
buf.append(mode)
buf.append(line)
return len(lines)
for row in self.rows:
lhs_index = row.lhs_index
rhs_index = row.rhs_index
if row.fail_count == 0:
row_line_count = add_row(' ', [cell_res.cell.content for cell_res in row.rhs])
lhs_line_count += row_line_count
rhs_line_count += row_line_count
else:
if lhs_index != -1:
lhs_line_count += add_row('-', [cell_res.cell.content for cell_res in row.lhs])
if rhs_index != -1:
rhs_line_count += add_row('+', [cell_res.cell.content for cell_res in row.rhs])
buf[line_ranges_index] = f'@@ -1,{lhs_line_count} +1,{rhs_line_count} @@\n'
def _repr_html_(self) -> str:
buf: list[str] = [style_tag()]
self._to_html(buf, False)
return ''.join(buf)
class TablesResult(NamedTuple):
tables: list[TableResult]
cell_fails: int
cell_count: int
row_fails: int
row_count: int
table_fails: int
table_count: int
def _repr_html_(self) -> str:
buf: list[str] = [style_tag()]
for table in self.tables:
table._to_html(buf, False)
return ''.join(buf)
def to_html(self, side_by_side: bool=False) -> str:
buf: list[str] = []
for table in self.tables:
table._to_html(buf, side_by_side)
return ''.join(buf)
def to_ansi(self, side_by_side: bool=False) -> str:
buf: list[str] = []
first = True
for table in self.tables:
if first:
first = False
else:
buf.append('\n')
table._to_ansi(buf, side_by_side)
return ''.join(buf)
def to_diff(self) -> str:
buf: list[str] = []
for table in self.tables:
table._to_diff(buf)
return ''.join(buf)
_RED_BG = '\x1B[41m'
_GREEN_BG = '\x1B[42m'
_WHITE_FG = '\x1B[37m'
_RESET = '\x1B[0m'
_BOLD = '\x1B[1m'
_LEFT_ONLY = _WHITE_FG + _RED_BG
_RIGHT_ONLY = _WHITE_FG + _GREEN_BG
_NON_PRINT = re.compile(r'[\x00-\x1F\x7F]')
_NON_PRINT_MAP = { chr(c): chr(0x2400 + c) for c in range(0, 0x20)}
_NON_PRINT_MAP['\x7F'] = '\u2421'
_non_print_repl = lambda m: _NON_PRINT_MAP[m[0]]
type Align = Literal['l', 'r', 'c']
def _format_table(table: Sequence[Sequence[tuple[str, Align, str]]], buf: list[str]) -> None:
# TODO: rowspan/colspan?
NON_PRINT_sub = _NON_PRINT.sub
table2: list[list[tuple[str, Align, list[str]]]] = [
[
(fmt, align, [
NON_PRINT_sub(_non_print_repl, line)
for line in cell.split('\n')
])
for fmt, align, cell in row
]
for row in table
]
widths: list[int] = [0] * max(map(len, table))
table3: list[tuple[int, list[tuple[str, Align, list[str]]]]] = []
for row in table2:
max_lines = 1
for col, (_, _, lines) in enumerate(row):
lines_len = len(lines)
width = max(map(wcswidth, lines))
if lines_len > max_lines:
max_lines = lines_len
if width > widths[col]:
widths[col] = width
if max_lines > 1:
for col, (_, _, lines) in enumerate(row):
while len(lines) < max_lines:
lines.append('')
table3.append((max_lines, row))
for max_lines, row in table3:
end_col = len(row) - 1
for line_index in range(max_lines):
for col, (fmt, align, lines) in enumerate(row):
width = widths[col]
line = lines[line_index]
diff = width - wcswidth(line)
if diff > 0:
match align:
case 'r':
line = ' ' * diff + line
case 'c':
half = diff // 2
line = ' ' * half + line + ' ' * (diff - half)
case _:
line += ' ' * diff
if col > 0:
buf.append(' ')
buf.append(fmt)
buf.append(line)
if fmt:
buf.append(_RESET)
if col == end_col:
buf.append('\n')
def _diff_row(lhs: TableRow, rhs: TableRow, window_size: int = DEFAULT_COLUMN_WINDOW) -> RowResult:
lhs_index = 0
rhs_index = 0
lhs_cells = lhs.cells
rhs_cells = rhs.cells
lhs_len = len(lhs_cells)
rhs_len = len(rhs_cells)
result: list[CellResult] = []
while True:
if lhs_index >= lhs_len:
if rhs_index < rhs_len:
result.extend(CellResult(None, cell) for cell in rhs_cells[rhs_index:])
rhs_index = rhs_len
break
if rhs_index >= rhs_len:
if lhs_index < lhs_len:
result.extend(CellResult(cell, None) for cell in lhs_cells[lhs_index:])
lhs_index = lhs_len
break
lhs_cell = lhs_cells[lhs_index]
rhs_cell = rhs_cells[rhs_index]
found = False
for offset in range(window_size + 1):
new_rhs_index = rhs_index + offset
new_lhs_index = lhs_index + offset
if new_rhs_index < rhs_len and lhs_cell.fuzzy_content == (new_rhs_cell := rhs_cells[new_rhs_index]).fuzzy_content:
if offset > 0:
result.extend(CellResult(None, cell) for cell in rhs_cells[rhs_index:new_rhs_index])
result.append(CellResult(lhs_cell, new_rhs_cell))
lhs_index += 1
rhs_index = new_rhs_index + 1
found = True
break
if new_lhs_index < lhs_len and rhs_cell.fuzzy_content == (new_lhs_cell := lhs_cells[new_lhs_index]).fuzzy_content:
if offset > 0:
result.extend(CellResult(cell, None) for cell in lhs_cells[lhs_index:new_lhs_index])
result.append(CellResult(lhs_cell, new_lhs_cell))
rhs_index += 1
lhs_index = new_lhs_index + 1
found = True
break
if not found:
result.append(CellResult(lhs_cell, None))
result.append(CellResult(None, rhs_cell))
lhs_index += 1
rhs_index += 1
lhs_res: list[RowResultCell] = []
rhs_res: list[RowResultCell] = []
fail_count = 0
for row in result:
row_lhs = row.lhs
row_rhs = row.rhs
if row_lhs is not None and row_rhs is not None:
lhs_res.append(RowResultCell(row_lhs, True))
rhs_res.append(RowResultCell(row_rhs, True))
elif row_lhs is not None:
lhs_res.append(RowResultCell(row_lhs, False))
fail_count += 1
elif row_rhs is not None:
rhs_res.append(RowResultCell(row_rhs, False))
fail_count += 1
return RowResult(result, fail_count, lhs_res, rhs_res, lhs.row_index, rhs.row_index)
def _make_one_sided_row_result(row: TableRow, side: Side) -> RowResult:
res: list[RowResultCell] = [RowResultCell(cell, False) for cell in row.cells]
lhs: list[RowResultCell]
rhs: list[RowResultCell]
cells: list[CellResult]
lhs_index: int
rhs_index: int
match side:
case Side.Left:
lhs = res
lhs_index = row.row_index
rhs_index = -1
rhs = []
cells = [CellResult(cell, None) for cell in row.cells]
case Side.Right:
rhs = res
rhs_index = row.row_index
lhs_index = -1
lhs = []
cells = [CellResult(None, cell) for cell in row.cells]
case _:
raise ValueError(f'illegal side: {side!r}')
fail_count = len(row.cells)
return RowResult(cells, fail_count, lhs, rhs, lhs_index, rhs_index)
def _make_one_sided_table_result(table: list[TableRow], side: Side, index: int = -1) -> TableResult:
rows = [_make_one_sided_row_result(row, side) for row in table]
return TableResult(
lhs = table if side == Side.Left else [],
rhs = table if side == Side.Right else [],
rows = rows,
cell_fails = sum((row_res.fail_count for row_res in rows), start=0),
cell_count = sum((len(row_res.cells) for row_res in rows), start=0),
row_fails = sum((int(row_res.fail_count > 0) for row_res in rows), start=0),
row_count = len(rows),
lhs_index = index if side == Side.Left else -1,
rhs_index = index if side == Side.Right else -1,
)
_SPACES = re.compile(r'\s+')
_DASHES = re.compile(r'[-–—]+')
_SPACES_sub = _SPACES.sub
_DASHES_sub = _DASHES.sub
_EXTRA_MAP = {
'°': 'o',
'′': "'",
}
def _extra_repl(m: Match) -> str:
return _EXTRA_MAP[m[0]]
_EXTRA = re.compile(f'[{"".join(_EXTRA_MAP)}]')
_EXTRA_sub = _EXTRA.sub
def _fuzzy_text(text: str) -> str:
fuzzy_text = _SPACES_sub('', text)
fuzzy_text = _DASHES_sub('-', fuzzy_text)
fuzzy_text = _EXTRA_sub(_extra_repl, fuzzy_text)
if fuzzy_text.endswith('....'):
no_dots = fuzzy_text.rstrip('.')
if no_dots:
fuzzy_text = no_dots
# K changes ⅛ to 1/8, ¹ to 1, etc.
fuzzy_text = normalize('NFKC', fuzzy_text)
fuzzy_text = fuzzy_text.casefold()
return fuzzy_text
def _fuzzy_table(rows: Sequence[Sequence[str]]) -> list[TableRow]:
return [
TableRow(
row_index,
[
TableCell(cell_index, cell, _fuzzy_text(cell))
for cell_index, cell in enumerate(row)
]
)
for row_index, row in enumerate(rows)
]
def _strict_table(rows: Sequence[Sequence[str]]) -> list[TableRow]:
return [
TableRow(
row_index,
[
TableCell(cell_index, cell, cell)
for cell_index, cell in enumerate(row)
]
)
for row_index, row in enumerate(rows)
]
def diff_table(
lhs: Sequence[Sequence[str]],
rhs: Sequence[Sequence[str]],
row_window: int = DEFAULT_ROW_WINDOW,
column_window: int = DEFAULT_COLUMN_WINDOW,
lhs_index: int = -1,
rhs_index: int = -1,
compare: CompareStrategy = CompareStrategy.Fuzzy,
) -> TableResult:
if compare == CompareStrategy.Fuzzy:
lhs_rows = _fuzzy_table(lhs)
rhs_rows = _fuzzy_table(rhs)
else:
lhs_rows = _strict_table(lhs)
rhs_rows = _strict_table(rhs)
return _diff_table(lhs_rows, rhs_rows, row_window, column_window, lhs_index, rhs_index)
def _diff_table(
lhs_rows: list[TableRow],
rhs_rows: list[TableRow],
row_window: int = DEFAULT_ROW_WINDOW,
column_window: int = DEFAULT_COLUMN_WINDOW,
lhs_index: int = -1,
rhs_index: int = -1,
) -> TableResult:
if row_window < 0:
raise ValueError(f'row_window has to be >= 0 but was: {row_window!r}')
if column_window < 0:
raise ValueError(f'column_window has to be >= 0 but was: {column_window!r}')
lhs_row_index = 0
rhs_row_index = 0
lhs_len = len(lhs_rows)
rhs_len = len(rhs_rows)
result: list[RowResult] = []
while True:
if lhs_row_index >= lhs_len:
if rhs_row_index < rhs_len:
result.extend(_make_one_sided_row_result(row, Side.Right) for row in rhs_rows[rhs_row_index:])
rhs_row_index = rhs_len
break
if rhs_row_index >= rhs_len:
if lhs_row_index < lhs_len:
result.extend(_make_one_sided_row_result(row, Side.Left) for row in lhs_rows[lhs_row_index:])
lhs_row_index = lhs_len
break
lhs_row = lhs_rows[lhs_row_index]
rhs_row = rhs_rows[rhs_row_index]
min_fail_result: RowResult|None = None
min_fail_lhs_index = lhs_row_index
min_fail_rhs_index = rhs_row_index
for offset in range(row_window + 1):
new_rhs_index = rhs_row_index + offset
new_lhs_index = lhs_row_index + offset
if new_rhs_index < rhs_len:
row_result = _diff_row(lhs_row, rhs_rows[new_rhs_index], column_window)
row_fail_count = row_result.fail_count
if min_fail_result is None or row_fail_count < min_fail_result.fail_count:
min_fail_result = row_result
min_fail_lhs_index = lhs_row_index
min_fail_rhs_index = new_rhs_index
if row_fail_count == 0:
break
if new_lhs_index < lhs_len:
row_result = _diff_row(rhs_row, lhs_rows[new_lhs_index], column_window)
row_fail_count = row_result.fail_count
if min_fail_result is None or row_fail_count < min_fail_result.fail_count:
min_fail_result = row_result
min_fail_lhs_index = new_lhs_index
min_fail_rhs_index = rhs_row_index
if row_fail_count == 0:
break
if min_fail_result is None:
# this should not happen (well if row_window < 0)
row_result = _diff_row(lhs_row, rhs_row, column_window)
result.append(row_result)
lhs_row_index += 1
rhs_row_index += 1
else:
if min_fail_lhs_index > lhs_row_index:
result.extend(_make_one_sided_row_result(row, Side.Left) for row in lhs_rows[lhs_row_index:min_fail_lhs_index])
if min_fail_rhs_index > rhs_row_index:
result.extend(_make_one_sided_row_result(row, Side.Right) for row in rhs_rows[rhs_row_index:min_fail_rhs_index])
result.append(min_fail_result)
lhs_row_index = min_fail_lhs_index + 1
rhs_row_index = min_fail_rhs_index + 1
cell_fails = sum((row_result.fail_count for row_result in result), start=0)
cell_count = sum((len(row_result.cells) for row_result in result), start=0)
row_fails = sum((int(row_result.fail_count > 0) for row_result in result), start=0)
return TableResult(
lhs = lhs_rows,
rhs = rhs_rows,
rows = result,
cell_fails = cell_fails,
cell_count = cell_count,
row_fails = row_fails,
row_count = len(result),
lhs_index = lhs_index,
rhs_index = rhs_index,
)
def diff_tables(
lhs: Sequence[Sequence[Sequence[str]]],
rhs: Sequence[Sequence[Sequence[str]]],
table_window: int = DEFAULT_TABLE_WINDOW,
row_window: int = DEFAULT_ROW_WINDOW,
column_window: int = DEFAULT_COLUMN_WINDOW,
compare: CompareStrategy = CompareStrategy.Fuzzy,
) -> TablesResult:
if table_window < 0:
raise ValueError(f'table_window has to be >= 0 but was: {table_window!r}')
make_table = _fuzzy_table if compare == CompareStrategy.Fuzzy else _strict_table
lhs_tables = list(map(make_table, lhs))
rhs_tables = list(map(make_table, rhs))
result: list[TableResult] = []
enum_lhs_tables = list(enumerate(lhs_tables))
enum_rhs_tables = list(enumerate(rhs_tables))
while enum_lhs_tables and enum_rhs_tables:
min_diff: TableResult|None = None
min_enum_lhs_index: int = -1
min_enum_rhs_index: int = -1
lhs_index, lhs_table = enum_lhs_tables[0]
rhs_index, rhs_table = enum_rhs_tables[0]
for offset in range(table_window + 1):
if offset < len(enum_lhs_tables):
offset_lhs_index, offset_lhs_table = enum_lhs_tables[offset]
diff = _diff_table(offset_lhs_table, rhs_table, row_window, column_window, offset_lhs_index, rhs_index)
if min_diff is None or min_diff.cell_fails > diff.cell_fails:
min_diff = diff
min_enum_lhs_index = offset
min_enum_rhs_index = 0
if diff.cell_fails == 0:
break
if offset < len(enum_rhs_tables):
offset_rhs_index, offset_rhs_table = enum_rhs_tables[offset]
diff = _diff_table(lhs_table, offset_rhs_table, row_window, column_window, lhs_index, offset_rhs_index)
if min_diff is None or min_diff.cell_fails > diff.cell_fails:
min_diff = diff
min_enum_lhs_index = 0
min_enum_rhs_index = offset
if diff.cell_fails == 0:
break
if min_diff is None:
# this should not happen (well if table_window < 0)
diff = _diff_table(lhs_table, rhs_table, row_window, column_window, lhs_index, rhs_index)
result.append(diff)
del enum_lhs_tables[0]
del enum_rhs_tables[0]
else:
result.append(min_diff)
del enum_lhs_tables[min_enum_lhs_index]
del enum_rhs_tables[min_enum_rhs_index]
if enum_lhs_tables:
result.extend(_make_one_sided_table_result(table, Side.Left, index) for index, table in enum_lhs_tables)
if enum_rhs_tables:
result.extend(_make_one_sided_table_result(table, Side.Right, index) for index, table in enum_rhs_tables)
cell_fails = sum((table_result.cell_fails for table_result in result), start=0)
cell_count = sum((table_result.cell_count for table_result in result), start=0)
row_fails = sum((table_result.row_fails for table_result in result), start=0)
row_count = sum((table_result.row_count for table_result in result), start=0)
table_fails = sum((int(table_result.cell_fails > 0) for table_result in result), start=0)
return TablesResult(
tables = result,
cell_fails = cell_fails,
cell_count = cell_count,
row_fails = row_fails,
row_count = row_count,
table_fails = table_fails,
table_count = len(result),
)
DEFAULT_COMPARE: CompareStrategy = CompareStrategy.Fuzzy
def main() -> None:
import sys
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-t', '--table-window', type=int, metavar='UINT', default=DEFAULT_TABLE_WINDOW, help=f'[default: {DEFAULT_TABLE_WINDOW}]')
ap.add_argument('-r', '--row-window', type=int, metavar='UINT', default=DEFAULT_ROW_WINDOW, help=f'[default: {DEFAULT_ROW_WINDOW}]')
ap.add_argument('-c', '--column-window', type=int, metavar='UINT', default=DEFAULT_COLUMN_WINDOW, help=f'[default: {DEFAULT_COLUMN_WINDOW}]')
ap.add_argument('-f', '--format', choices=['html', 'ansi', 'diff'], default=None, help='[default: from extension of --output file, ansi for stdout]')
ap.add_argument('-o', '--output', default='-', help='Use "-" for stdout. [default: -]')
ap.add_argument('--side-by-side', action='store_true', default=False, help="Show tables side by side.")
ap.add_argument('--compare', choices=[compare.value for compare in CompareStrategy], default=DEFAULT_COMPARE.value, help=f'[default: {DEFAULT_COMPARE.value}]')
ap.add_argument('files', nargs='+', metavar='files... :: files...')
args = ap.parse_args()
def _load_csv(filename: str) -> list[list[str]]:
with open(filename, 'r', encoding='utf-8-sig') as file1:
return list(csv.reader(file1, dialect='excel-tab' if filename.lower().endswith('.tsv') else 'excel'))
files: list[str] = args.files
lhs_files: list[str]
rhs_files: list[str]
try:
delim_index = files.index('::')
except ValueError:
if len(files) == 2:
lhs_files = [files[0]]
rhs_files = [files[1]]
else:
print('Lists of CSV files need to be separated by "::".', file=sys.stderr)
ap.print_usage()
sys.exit(1)
else:
lhs_files = files[:delim_index]
rhs_files = files[delim_index + 1:]
lhs_tables = [_load_csv(filename) for filename in lhs_files]
rhs_tables = [_load_csv(filename) for filename in rhs_files]
compare = CompareStrategy(args.compare)
result = diff_tables(lhs_tables, rhs_tables, args.table_window, args.row_window, args.column_window, compare)
out_format: Literal['html', 'ansi', 'diff']|None = args.format
output: str = args.output
if out_format is None:
if output == '-':
out_format = 'ansi'
else:
ext = splitext(output)[1].casefold()
match ext:
case 'diff' | 'patch':
out_format = 'diff'
case 'html' | 'xhtml':
out_format = 'html'
case 'ansi':
out_format = 'ansi'
case _:
out_format = 'html'
match out_format:
case 'html':
htitle = h(f'Comparing {len(lhs_files)} Tables with {len(rhs_files)} Tables')
html = result.to_html(side_by_side=args.side_by_side)
text = f'''\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{htitle}</title>
<style type="text/css">
body {{
font-family: sans-serif;
}}
{STYLE}
</style>
</head>
<body>
<h1>{htitle}</h1>
{html}
</body>
</html>
'''
case 'ansi':
text = result.to_ansi(side_by_side=args.side_by_side)
case 'diff':
text = result.to_diff()
case _:
raise ValueError(f'illegal format: {args.format!r}')
if output == '-':
sys.stdout.write(text)
sys.stdout.flush()
else:
with open(output, 'wt') as outfile:
outfile.write(text)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment