Skip to content

Instantly share code, notes, and snippets.

@gvx
Created May 3, 2009 21:53
Show Gist options
  • Save gvx/106168 to your computer and use it in GitHub Desktop.
Save gvx/106168 to your computer and use it in GitHub Desktop.
A simple patch script in Python
#By Robin Wellner (gvx)
#I hereby waive copyright and related or neighboring rights to this work
#See the Creative Commons Zero Waiver at <http://creativecommons.org/publicdomain/zero/1.0/>
import sys
diff_file = sys.stdin.read().split('\n')
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = diff_file[0][4:].split('\t', 2)[0]
try:
f = open(filename)
except:
sys.stderr.write("Fatal: File could not be opened.\n")
sys.exit(1)
old_file = f.read().split('\n')
f.close()
diff_file.pop(0);diff_file.pop(0)
for line in diff_file:
try:
first, rest = line[0], line[1:]
except IndexError:
first = None
if first == '@':
new_index = int(rest.split('+', 2)[1].split(',', 2)[0]) - 1
elif first == '+': #new line
old_file.insert(new_index, rest)
new_index += 1
elif first == '-': #deleted line
old_file.pop(new_index)
else:
#if ' ' or '\', simply ignore
new_index += 1
sys.stdout.write('\n'.join(old_file))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment