1
0
mirror of https://github.com/samba-team/samba.git synced 2025-12-18 08:23:51 +03:00

python/colour: add a colour diff helper

Sometimes colour can help show what is different between two strings.

This is roughly the same as

`git diff --no-index --color-words=. <a> <b>`.

Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>
This commit is contained in:
Douglas Bagnall
2023-08-17 14:20:12 +12:00
committed by Andrew Bartlett
parent a24ba4ea22
commit f58372cca5

View File

@@ -141,3 +141,35 @@ def colour_if_wanted(*streams, hint='auto'):
else:
switch_colour_off()
return wanted
def colourdiff(a, b):
"""Generate a string comparing two strings or byte sequences, with
differences coloured to indicate what changed.
Byte sequences are printed as hex pairs separated by colons.
"""
from difflib import SequenceMatcher
out = []
if isinstance(a, bytes):
a = a.hex(':')
if isinstance(b, bytes):
b = b.hex(':')
a = a.replace(' ', '')
b = b.replace(' ', '')
s = SequenceMatcher(None, a, b)
for op, al, ar, bl, br in s.get_opcodes():
if op == 'equal':
out.append(a[al: ar])
elif op == 'delete':
out.append(c_RED(a[al: ar]))
elif op == 'insert':
out.append(c_GREEN(b[bl: br]))
elif op == 'replace':
out.append(c_RED(a[al: ar]))
out.append(c_GREEN(b[bl: br]))
else:
out.append(f' --unknown diff op {op}!-- ')
return ''.join(out)