Skip to content

Instantly share code, notes, and snippets.

@eliemichel
Last active September 9, 2024 14:20
Show Gist options
  • Save eliemichel/3af4a0cdac2434e16e74f96516571ae7 to your computer and use it in GitHub Desktop.
Save eliemichel/3af4a0cdac2434e16e74f96516571ae7 to your computer and use it in GitHub Desktop.
Resolve conflicted areas of a file in favor of theirs or ours and leave correctly merged areas as is
# This is an automation of https://stackoverflow.com/questions/71783590/git-merge-strategy-option-theirs-for-individual-files
# Example:
# git_resolve.py --theirs path/to/some/file
import os
import argparse
from shutil import copyfile
import subprocess
parser = argparse.ArgumentParser(description='Resolve conflicted areas of a file during a git merge')
parser.add_argument('path', type=str, help='Path of the file for which to resolve merge conflict')
parser.add_argument('--theirs', action='store_true', help='Use their version wherever there is a conflict')
parser.add_argument('--ours', action='store_true', help='Use our version wherever there is a conflict')
args = parser.parse_args()
def run(cmd, outfilename=None):
if outfilename is not None:
with open(outfilename, "w") as outfile:
subprocess.run(cmd, stdout=outfile)
else:
subprocess.run(cmd)
def main(args):
if args.theirs and args.ours:
print("Error! You must chose either --theirs or --ours but not both")
exit(1)
elif args.theirs:
which_one = "--theirs"
elif args.ours:
which_one = "--ours"
else:
print("Error! You must chose one of --theirs or --ours")
exit(1)
run(["git", "show", f":1:{args.path}"], f"{args.path}.base")
run(["git", "show", f":2:{args.path}"], f"{args.path}.ours")
run(["git", "show", f":3:{args.path}"], f"{args.path}.theirs")
run(["git", "merge-file", which_one, f"{args.path}.ours", f"{args.path}.base", f"{args.path}.theirs"])
copyfile(f"{args.path}.ours", f"{args.path}")
os.remove(f"{args.path}.base")
os.remove(f"{args.path}.base")
os.remove(f"{args.path}.theirs")
main(parser.parse_args())
@jbowman-selectech
Copy link

should probably be os.remove(f"{args.path}.ours") as the base file is removed twice here, but the ours file is left in place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment