Count number of mergeable commits using git

Viewed 104

I have a script that auto merges a feature branch into master. It runs periodically.

I want the script to check that the feature branch does in fact have commits to be merged. If there are no commits the script should exit.

I’ve tried the following:

git rev-list --count HEAD

Run while on the feature branch called ‘test’ with no commits this is returning a value of 1, so the script doesn’t exit, even though it should because there are no commits to merge.

Note that I ran git fetch —all before all of these commands.

Also tried the following:

Tried:

git rev-list --count master..

Resulted in error:

fatal: ambiguous argument 'master..': unknown revision or path not in the working tree.

Tried:

git rev-list --count master

Resulted in error:

fatal: ambiguous argument 'master': unknown revision or path not in the working tree.

Tried:

git rev-list --count master..test

Resulted in error:

fatal: ambiguous argument 'master..test': unknown revision or path not in the working tree.

How do I determine (from a script) if there are commits to merge?

1 Answers

The command you are using is absolutely correct. The error you are seeing in your case means that master as a branch is not available in the local file system of the repository from where you are running this command.

To make this work properly, you'd want to put in the right reference.

git rev-list --count origin/master

Assuming that the remote you want to check against, is named origin.

Additionally you can do some shell magic to make it work like you want, the below works with zsh:

# merge branch 
commit_distance=$(git rev-list --count origin/master)
if [ $commit_distance -eq 0 ];
then
  exit 1
fi

# ... the remaining script
Related