Back to index

moin  1.9.0~rc2
diff_text.py
Go to the documentation of this file.
00001 # -*- coding: iso-8859-1 -*-
00002 """
00003     MoinMoin - simple text diff (uses difflib)
00004 
00005     @copyright: 2006 MoinMoin:ThomasWaldmann
00006     @license: GNU GPL, see COPYING for details.
00007 """
00008 from MoinMoin.support import difflib
00009 
00010 def diff(oldlines, newlines, **kw):
00011     """
00012     Find changes between oldlines and newlines.
00013 
00014     @param oldlines: list of old text lines
00015     @param newlines: list of new text lines
00016     @keyword ignorews: if 1: ignore whitespace
00017     @rtype: list
00018     @return: lines like diff tool does output.
00019     """
00020     false = lambda s: None
00021     if kw.get('ignorews', 0):
00022         d = difflib.Differ(false)
00023     else:
00024         d = difflib.Differ(false, false)
00025 
00026     lines = list(d.compare(oldlines, newlines))
00027 
00028     # return empty list if there were no changes
00029     changed = 0
00030     for l in lines:
00031         if l[0] != ' ':
00032             changed = 1
00033             break
00034     if not changed: return []
00035 
00036 #    if not "we want the unchanged lines, too":
00037 #        if "no questionmark lines":
00038 #            lines = [line for line in lines if line[0] != '?']
00039 #        return lines
00040 
00041 
00042     # calculate the hunks and remove the unchanged lines between them
00043     i = 0              # actual index in lines
00044     count = 0          # number of unchanged lines
00045     lcount_old = 0     # line count old file
00046     lcount_new = 0     # line count new file
00047     while i < len(lines):
00048         marker = lines[i][0]
00049         if marker == ' ':
00050             count = count + 1
00051             i = i + 1
00052             lcount_old = lcount_old + 1
00053             lcount_new = lcount_new + 1
00054         elif marker in ['-', '+']:
00055             if (count == i) and count > 3:
00056                 lines[:i-3] = []
00057                 i = 4
00058                 count = 0
00059             elif count > 6:
00060                 # remove lines and insert new hunk indicator
00061                 lines[i-count+3:i-3] = ['@@ -%i, +%i @@\n' %
00062                                         (lcount_old, lcount_new)]
00063                 i = i - count + 8
00064                 count = 0
00065             else:
00066                 count = 0
00067                 i += 1
00068             if marker == '-': lcount_old = lcount_old + 1
00069             else: lcount_new = lcount_new + 1
00070         elif marker == '?':
00071             lines[i:i+1] = []
00072 
00073     # remove unchanged lines a the end
00074     if count > 3:
00075         lines[-count+3:] = []
00076 
00077     return lines
00078