Skip to content

Commit

Permalink
bugfix for python 2.6
Browse files Browse the repository at this point in the history
  • Loading branch information
jedie committed Jun 11, 2012
1 parent 10a8d09 commit 4e47a28
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions reversion_compare/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,23 @@ def highlight_diff(diff_text):
# Change from ndiff to unified_diff if old/new values are more than X lines:
LINE_COUNT_4_UNIFIED_DIFF = 4


def format_range(start, stop):
"""
Convert range to the "ed" format
difflib._format_range_unified() is new in python 2.7
see also: https://github.com/jedie/django-reversion-compare/issues/5
"""
# Per the diff spec at http://www.unix.org/single_unix_specification/
beginning = start + 1 # lines start numbering with one
length = stop - start
if length == 1:
return '{0}'.format(beginning)
if not length:
beginning -= 1 # empty ranges begin at line just before the range
return '{0},{1}'.format(beginning, length)


def unified_diff(a, b, n=3, lineterm='\n'):
r"""
simmilar to the original difflib.unified_diff except:
Expand All @@ -77,21 +94,14 @@ def unified_diff(a, b, n=3, lineterm='\n'):
started = False
for group in difflib.SequenceMatcher(None, a, b).get_grouped_opcodes(n):
first, last = group[0], group[-1]
try:
file1_range = difflib._format_range_unified(first[1], last[2])
file2_range = difflib._format_range_unified(first[3], last[4])
except AttributeError:
# difflib._format_range_unified() is new in python 2.7
# see also: https://github.com/jedie/django-reversion-compare/issues/5
i1, i2, j1, j2 = first[1], last[2], first[3], last[4]
file1_range = "%i,%i" % (i1 + 1, i2 - i1)
file2_range = "%i,%i" % (j1 + 1, j2 - j1)
file1_range = format_range(first[1], last[2])
file2_range = format_range(first[3], last[4])

if not started:
started = True
yield '@@ -{} +{} @@'.format(file1_range, file2_range)
yield '@@ -{0} +{1} @@'.format(file1_range, file2_range)
else:
yield '{}@@ -{} +{} @@'.format(lineterm, file1_range, file2_range)
yield '{0}@@ -{1} +{2} @@'.format(lineterm, file1_range, file2_range)

for tag, i1, i2, j1, j2 in group:
if tag == 'equal':
Expand Down

0 comments on commit 4e47a28

Please sign in to comment.