Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git check if commit is merge commit from master

Tags:

git

jenkins

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?

like image 575
Dawe Avatar asked Feb 25 '19 13:02

Dawe


1 Answers

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

Background

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.

Disclaimer

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!

like image 156
Alexandre Cassagne Avatar answered Oct 23 '22 16:10

Alexandre Cassagne