Skip to content

Instantly share code, notes, and snippets.

@cwilper
Created May 12, 2021 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwilper/e1ef00a83a4b34bc9a4d3ebd16ff6840 to your computer and use it in GitHub Desktop.
Save cwilper/e1ef00a83a4b34bc9a4d3ebd16ff6840 to your computer and use it in GitHub Desktop.
git-lastmerge - find the last time one branch was merged into another
#!/usr/bin/env bash
#
# script : git-lastmerge.sh
# purpose : Find the last time one branch was merged into another
# usage : git lastmerge [source_branch [dest_ref ["merge-id"|"parent-id"]]]
# created : May 2021 by cwilper
#
# How it works:
#
# * Looks for the last commit message saying "Merged branch 'x'"
# * Identifies which of the parents of that commit is the one in the source branch
#
# Setting it up (optional, can be invoked directly too):
#
# * Put the script somewhere in your PATH (e.g. ~/bin) and make it executable (e.g. chmod 755)
# * In your ~/.gitconfig file, add an entry under [alias] as follows:
# lastmerge= !sh -c 'git-lastmerge.sh $1 $2 $3' -
#
# Example: Show the last time main was merged into the current branch
#
# > git lastmerge
#
# Example: Show the last time the dev branch was merged into the test branch
#
# > git lastmerge dev test
#
# Example: Get the merge commit id and parent commit id of the above only
#
# > git lastmerge dev test merge-id
# > git lastmerge dev test parent-id
#
# Example: Show the last time main was merged into a commit in dev which was merged into test
#
# > git lastmerge main $(git lastmerge dev test parent-id)
#
declare -a arr
source_branch="$1"
[[ $source_branch ]] || source_branch=main
dest_ref="$2"
[[ $dest_ref ]] || dest_ref=$(git branch --show-current)
while read -r line; do
arr=($line)
if [[ $line =~ ^Merge: ]]; then
parent1=${arr[1]}
parent2=${arr[2]}
elif [[ $line =~ ^commit ]]; then
merge_commit=${arr[1]}
elif [[ $line =~ ^Author: ]]; then
merger="${arr[1]} ${arr[2]}"
elif [[ $line =~ ^Date: ]]; then
mergedate="${arr[1]} ${arr[2]} ${arr[3]} ${arr[5]}"
fi
done < <(git log $dest_ref|grep -B 5 "Merge .*branch '$source_branch'"|head -4)
if [[ $parent1 ]]; then
normal=$(tput sgr0)
git branch --contains $parent1 | grep " ${source_branch}$" > /dev/null 2>&1
if [[ $? == 0 ]]; then
parent_commit=$parent1
else
parent_commit=$parent2
fi
if [[ $3 == merge-id ]]; then
echo $merge_commit
elif [[ $3 == parent-id ]]; then
echo $parent_commit
else
bold=$(tput bold)
echo "${bold}Merge Commit${normal}"
git show -s $merge_commit
echo
echo "${bold}Parent Commit${normal}"
git show -s $parent_commit
fi
else
red=$(tput setaf 1)
echo "${red}Couldn't find the last merge of $source_branch into $dest_ref${normal}"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment