Last active
February 15, 2017 10:39
-
-
Save luxcem/85f1a416087efb0ca82060336562200f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def html_diff(val1, val2): | |
from difflib import SequenceMatcher | |
if val1 is None or val2 is None: | |
return (val1, val2) | |
diff = SequenceMatcher(None, val1, val2) | |
op_codes = diff.get_opcodes() | |
offset1 = 0 | |
offset2 = 0 | |
for op_code in op_codes: | |
op, i1, i2, j1, j2 = op_code | |
if op != 'equal': | |
if i1 != i2: | |
to_insert = '<span class="diff diff-{code}">'.format(code=op) | |
val1 = val1[:i1 + offset1] + to_insert + val1[i1 + offset1:] | |
offset1 += len(to_insert) | |
to_insert = '</span>' | |
val1 = val1[:i2 + offset1] + to_insert + val1[i2 + offset1:] | |
offset1 += len(to_insert) | |
if j1 != j2: | |
to_insert = '<span class="diff diff-{code}">'.format(code=op) | |
val2 = val2[:j1 + offset2] + to_insert + val2[j1 + offset2:] | |
offset2 += len(to_insert) | |
to_insert = '</span>' | |
val2 = val2[:j2 + offset2] + to_insert + val2[j2 + offset2:] | |
offset2 += len(to_insert) | |
return (val1, val2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment