Skip to content

Instantly share code, notes, and snippets.

@cb109
Last active August 16, 2024 08:26
Show Gist options
  • Save cb109/bf7246cf1f128a7cad30d90d8f71dbb4 to your computer and use it in GitHub Desktop.
Save cb109/bf7246cf1f128a7cad30d90d8f71dbb4 to your computer and use it in GitHub Desktop.
Check for any merge conflicts as preparation for git pull (upstream VS local branch)
#!/bin/bash
# In this example we want to execute 'git pull' on the local 'master' branch, but we
# want to make sure that pull won't introduce conflicts and by that a broken checkout.
# The script below will do an in-memory merge of the upstream master and local master
# and exit with a non-zero code if that merge produced any conflicts.
#
# A snippet like this is useful for deployment scripts that involve 'git pull' to
# prevent breaking production if for some reason a conflict has bypassed CI.
#
# Tools like the GitHub Pull Request interface does this under the hood already and
# warns you about potential conflicts, while preventing a merge. For custom tooling,
# this script serves as an equivalent for that.
set -e
# Get tracked upstream for local branch: https://stackoverflow.com/a/16879922
upstream_master="$(git rev-parse --abbrev-ref master@{upstream})"
merge_this=$upstream_master
into_that=master
# Merge in-memory, extract conflict from diff: https://stackoverflow.com/a/63777004
git fetch --all
conflict="$(git merge-tree $(git merge-base $merge_this $into_that) $into_that $merge_this | sed -ne '/^\+<<</,/^\+>>>/ p')"
if [ -z "$conflict" ]
then
printf "Testing if we can merge $merge_this -> $into_that, no conflicts found, good to go!\n"
else
printf "Testing if we can merge $merge_this -> $into_that, but there are conflicts:\n\n"
# Quote variable on echo to preserve newlines: https://stackoverflow.com/a/22101842
printf "$conflict"
printf "\n\nAborting merge, please resolve the conflicts and push the fix before trying again.\n"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment