Thursday, May 07, 2009

I need a diff (or patch) manipulation utility, but unfortunately I have not found one, then I wrote one, of course, it's in Python.



#!/usr/bin/python

import sys, os

# Usage: diff-filter [-v] path1 path2 ...
# <INPUT >OUTPUT
if len(sys.argv) <= 1:

print "Usage: %s [-v] path1 path2 ... <INPUT" % \
os.path.basename(sys.argv[0])

sys.exit(1)

# some global variables
inChunk = True

strip = 1
matched = False
buffer = ''

invert = False

# to invert the filter
if sys.argv[1] == '-v':

invert = True
del sys.argv[1]

# the main filter
while True:
line = sys.stdin.readline()

if not line:
break

if line.startswith("--- ") or \
line.startswith("diff") or \
line.startswith("Binary") or \
line.startswith("Index"):

matched = False
inChunk = False

if line.startswith("diff") or \
line.startswith("Binary") or \
line.startswith("Index"):

buffer += line
continue
else:
path = line.split()[1]

slash = path.find('/')
path = path[slash+1:]

for arg in sys.argv[1:]:
if path.startswith(arg):

matched = True
break
else:
matched = False

if invert:
matched = not matched
if not matched:

buffer = ''

if inChunk:
print line,

if matched:
if buffer:
print buffer,

buffer = ''
print line,


It also can be reached by the ubuntu paste service:



http://paste.ubuntu.com/166435/

Application field: if you have a big diff generated by "diff -R", and want to split it according to some seperate path or components, you can use this. Happy hacking!

No comments: