Not necessarily better, but if you are just looking for revision counts:
The number of commits you are "ahead of" a remote-tracking branch is the number of commits that are reachable from your branch, but not from that remote-tracking branch:
git rev-list --count origin/master..master
and
git rev-list --count fork/master..master
respectively.
The number of commits you are "behind" a remote-tracking branch is the symmetric opposite: the number of commits that are reachable from the remote-tracking branch, but not from your own branch:
git rev-list --count master..origin/master
git rev-list --count master..fork/master
These are the various counts that git status
(or git branch -v
) show. Having origin/master
as the current upstream for master
means that git status
will count master..origin/master
and origin/master..master
.
Pictorially, this might look something like this, where each uppercase letter stands for one of those big ugly commit hash IDs:
F--G <-- origin/master
/
...--B--C--D--E <-- master
\
H--I--J <-- fork/master
The count of commits on master
that are not on fork/master
is 1: that's commit E
. Commit D
is on both origin/master
and fork/master
, and so are C
and earlier, so there is just the one commit. Meanwhile the count of commits on fork/master
that are not on master
is 3: those are commits J
, I
, and H
(as with all things Git we work backwards, from newer to older). H
's parent commit D
is reachable from master
by working backwards, so we stop counting there.
Similarly, the count for origin/master..master
is 2 (E
and D
), and the count for master..origin/master
is also 2 (but these are G
and F
this time).
You can even get a count for origin/master..fork/master
—it's 4: J
, I
, H
, and D
—and for fork/master..origin/master
(it's 2: exercise: which 2?). (You cannot get this from git status
because you cannot set an upstream for a remote-tracking branch. You must run git rev-list
directly.)
A shortcut (advanced study item)
To avoid having to run git rev-list --count
twice, you can get both counts at once. Using a symmetric difference selector (see the gitrevisions documentation) such as origin/master...master
—note the three dots instead of two—we can select all commits that are reachable from either tip commit, but not from both tip commits. Adding --left-right
makes git rev-list
keep track of which tip resulted in selecting the commit, and adding --count
then prints both counts, separately. So:
git rev-list --left-right --count origin/master...master
tells us how many we're "behind" (left side) and "ahead" (right side), in one command. (Swap the two names and you get "ahead" first, then "behind".)