Skip to content

Instantly share code, notes, and snippets.

@mountainstorm
Created September 9, 2014 22:23
Show Gist options
  • Save mountainstorm/0cbbc1dcfa817804d205 to your computer and use it in GitHub Desktop.
Save mountainstorm/0cbbc1dcfa817804d205 to your computer and use it in GitHub Desktop.
Simple unified diff processing script, which takes lineno's for file a, and tells you where they will be in file b. The idea is it should be really useful for tracking issues once you've done a source code review
#!/usr/bin/python
# coding: utf-8
# Copyright (c) 2014 Mountainstorm
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Processes the output of 'diff -w -U 0 file1 file2'
# tracking lines which have moved
#
import sys
import re
_diffline = re.compile(r'@@ ([-+])?([0-9]*)(,([0-9]*))? ([-+])?([0-9]*)(,([0-9]*))? @@')
def track_lines(stream, inlines):
retval = []
i = 0
delta = 0
for line in stream.readlines():
if i == len(inlines):
break
line = line.decode(u'utf-8')
# find diff line locations
m = _diffline.search(line)
if m is not None:
g = m.groups()
aline = int(g[1])
alen = 0 if g[3] is None else max(0, int(g[3]) - 1)
bline = int(g[5])
blen = 0 if g[7] is None else max(0, int(g[7]) - 1)
# check for removed items
while i < len(inlines):
if inlines[i] < aline:
retval.append(inlines[i] + delta) # stuff before this change
elif inlines[i] >= aline and inlines[i] < aline+alen:
retval.append(None) # stuff within change (removed)
else:
break
i += 1
delta = (bline+blen - aline-alen)
# sort out any remaining lines
while i < len(inlines):
retval.append(inlines[i] + delta)
i += 1
return retval
if __name__ == u'__main__':
oldissues = [20, 114, 554, 4799, 5318, 5321, 7904, 7909, 7930, 7940]
print oldissues
print track_lines(sys.stdin, oldissues)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment