Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplest possible way git can output the number of commits between "branch" and "remotes/origin/branch"

Tags:

git

python

I'm working with custom a build system that manages a large number of git repositories and written primarily in python.

It would save me a lot of time if I could write a command that would report the current branch of all repositories, then report if the head of "branch" is the same as the head of "remotes/origin/branch".

We already have a command that will run a shell command inside every git repository, what I'm looking for is a method of getting some simply formatted information from git with regards to the relative position of branch and remotes/origin/branch. Something which is either going to be number of commits difference or a simple boolean value.

What's the method of getting this information out of git which is going to minimize the amount of parsing and processing I've got to do on the python side?

like image 500
Sparky Avatar asked Apr 16 '13 12:04

Sparky


3 Answers

If you have a new enough version of git, you can use:

$ git rev-list --count --left-right branch...origin/branch
2   1

The first number if the number of commits branch is ahead of origin/branch, and the second is the number of commits behind. So this branch has two commits that are not upstream yet, and there's one commit upstream that is not in my local branch yet.

I believe it was 1.6 or 1.7 when --count was introduced.

like image 90
John Szakmeister Avatar answered Oct 18 '22 00:10

John Szakmeister


git status shows how many commits you are ahead/behind the remote tracking branch. You need to perform git fetch first though, because otherwise git cannot know if anything new went into remote.

like image 38
akostadinov Avatar answered Oct 18 '22 00:10

akostadinov


If branch is ensured to be ancestor of origin/branch (i.e fast-forwardable), then

git log --oneline branch..origin/branch

should print the commits in between them, each in one line. You can count the lines either in python or wc -l .

Not sure if simple and general solution exists. There might be no common ancestor for origin/branch and branch, if orphan branch is involved.

like image 1
Jokester Avatar answered Oct 18 '22 01:10

Jokester