Skip to content

Instantly share code, notes, and snippets.

@jameshiew
Forked from tmiller/merge
Last active October 24, 2018 18:47
Show Gist options
  • Select an option

  • Save jameshiew/722b0da8a2de5c17676075dcb870b787 to your computer and use it in GitHub Desktop.

Select an option

Save jameshiew/722b0da8a2de5c17676075dcb870b787 to your computer and use it in GitHub Desktop.
Bash script to pull latest master and do a simple merge into all local branches on a best-effort basis
#!/usr/bin/env bash
# Adapted from https://gist.github.com/tmiller/5222478
# Merges the master branch into all other branches
#
# Process:
#
# - Save the name of the current branch, stash everything
# - If the current branch is not master then checkout master.
# - Pull the latest changes for master from its upstream branch.
# - Loop over each local branch.
# - If the branch is not master.
# - Checkout the branch.
# - Attempt to merge master into the branch with a default commit
# message, aborting if there are conflicts
# - If the current branch is not the saved branch name checkout the saved
# branch name
# - Unstash everything
#. - Output any branches for which merging master did not succeed simply
# Returns the names of all the local branches
local_branches() {
git for-each-ref --format="%(refname:short)" refs/heads
}
# Returns the name of the current branch
current_branch() {
git symbolic-ref --short HEAD
}
saved_branch=$(current_branch)
stash_name="${saved_branch}_$(date +"%D-%T")"
git stash push -m ${stash_name}
if [[ $? -ne 0 ]]; then
echo "Something went wrong when trying to stash local changes, will not continue"
fi
[[ "${saved_branch}" != "master" ]] && git checkout "master"
git pull
declare -a conflicting_branches
for branch in $(local_branches); do
if [[ "${branch}" != "master" ]]; then
echo
git checkout "${branch}"
git merge "master" -m "Merge in latest master"
if [[ $? -ne 0 ]]; then
echo "Could not merge ${branch}, aborting..."
git merge --abort
conflicting_branches+=(${branch})
fi
fi
done
echo
[[ "${saved_branch}" != "$(current_branch)" ]] && git checkout "${saved_branch}"
echo
if [ ${#conflicting_branches[@]} -eq 0 ]; then
echo "No conflicting branches"
else
echo "# Conflicting branches"
for conflicting_branch in "${conflicting_branches[@]}"; do
echo "$conflicting_branch"
done
fi
git stash list | grep ${stash_name}
if [[ $? -ne 0 ]]; then
echo "No stash called '${stash_name}' is present, maybe no stash was needed"
else
git stash apply stash^{/${stash_name}} # TODO(jhiew): is this robust?
if [[ $? -ne 0 ]]; then
echo "Could not apply stash ${stash_name}"
fi
# TODO(jhiew): drop stash automagically
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment