Skip to content

Instantly share code, notes, and snippets.

@wbbradley
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save wbbradley/0408f8151dedb467fe5f to your computer and use it in GitHub Desktop.

Select an option

Save wbbradley/0408f8151dedb467fe5f to your computer and use it in GitHub Desktop.
merger - a command line tool for resolving merge conflicts with p4merge
#!/usr/bin/env python
#
# Author: wbbradley
# Created: Originally written in Perl in 2010
# Edited: Rewritten in Python in 2014
#
# You'll need to have P4Merge installed. It's free, and
# you can find it here:
# http://lmgtfy.com/?q=P4Merge+Tool+Download
#
from subprocess import Popen, PIPE, STDOUT
def system(cmd, shell=False):
if isinstance(cmd, (str, unicode)):
print "Running {}".format(cmd)
else:
print "Running {}".format(' '.join(cmd))
proc = Popen(cmd, shell=shell, stderr=STDOUT, stdout=PIPE)
out, err = proc.communicate()
if err:
raise Exception('Error {} running {}'.format(err, cmd))
return out
merges = {}
lines = system(['git', 'ls-files', '-u']).split('\n')
for line in lines:
line = line.split()
if line:
attrs, sha, obj_type, filename = line
merges[filename] = merges.get(filename) or {}
merges[filename][obj_type] = sha
for filename, objects in merges.iteritems():
if len(objects.keys()) == 3:
head_file = "/var/tmp/head_file"
merge_file = "/var/tmp/merge_file"
ancestor_file = "/var/tmp/ancestor_file"
system("git show {} > {}".format(objects['1'], ancestor_file), shell=True)
system("git show {} > {}".format(objects['2'], head_file), shell=True)
system("git show {} > {}".format(objects['3'], merge_file), shell=True)
p4merge_cmd = [
"/Applications/p4merge.app/Contents/Resources/launchp4merge",
ancestor_file, head_file, merge_file, filename
]
system(p4merge_cmd)
print "+"*79
print "Here's the diff that remains from your merge of {}".format(filename)
print system(['git', 'diff', '--', filename])
key = raw_input("Would you like to run 'git add {}'? [Ynpq]".format(filename))
if key in ['Y', 'y', 'p'] or key == '':
print system(['git', 'add', '-p' if key == 'p' else '', filename])
print system("git status | grep both", shell=True)
else:
if key == 'q':
system("git status | grep both", shell=True)
sys.exit()
else:
print "Skipping merge of {}...".format(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment