I am building jenkins job and I am making hotfix. I have hotfix branch which is merged into master, then this commit is tagged with minor version. After this job is merging master into develop. I need to detect this commit. If it is from merge from master then build it with tagged version. When it is not, just build latest. Is there easy way to detect if it is merge commit from master?
Try the following snippet as a script to test whether the commit is a merge.
#!/bin/bash
commit_hash=$(git rev-parse HEAD)
parent_hashes=`git rev-list --parents -n 1 $commit_hash`
parent_count=`wc -w <<< $parent_hashes`
if [[ $parent_count -gt 2 ]]
then
p=`git name-rev $parent_hashes | xargs -0 | grep -e '^\S\+ master$'`
if [[ ! -z $p ]]
then
echo "merged; master"
exit 0
else
echo "merged; non-master"
exit 2
fi
else
echo "not merged"
exit 1
fi
In git, a merge simply means that a commit has more than one parent.
The command git rev-list --parents -n 1 $commit_hash
returns a set of commit hashes that are parents of this commit.
To check if there are more than 2 parents*, wc -w <<< $parent_hashes
is tested.
piping it through xargs
, git name-rev
will gather the name of each commit's ref so that we can test if it is master
– this is what the grep -e (fancy regex)
command does
Finally, the command prints some debug text and returns an exit code depending on the situation.
This script is not production ready. There may be some edge-cases I have not considered; if you find any, please drop me a line and I will correct this answer.
* Note. git rev-list --parents [...]
also returns the hash of this commit. I have not investigated why, but if you know, let me know!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With