How to get correct git rev-list count with a shallow clone?

Viewed 1147

I found it a super smart idea to add the git revision number to my project version during the gradle build, like major.minor.commit. This is realized via

git rev-list --count HEAD

Now I'm using gitlab ci which only gets the latest 50 commits:

Fetching changes with git depth set to 50...

So I end up with a version number of 50 all the time. Long story short, how do I get the correct count with a shallow git clone?

1 Answers

(Note: this only addresses computing the count, not whether that's a good idea. As to whether it's a good idea: consider what happens if you have three copies of the repository, one being from some central point, the second one being user A's to which user A added one commit, and the third being user B's to which user B added one commit. What is the count in user A's repository? What is it in user B's?)

You don't.

Git can't look at some other repository's commits (well, except when you use git fetch and they give your Git those commits for your Git to stuff into its own repository—but at that point, those aren't the other repository's commits: they're yours now, or perhaps more accurately, they're shared now).

The git rev-list command enumerates—or with --count, just counts—commits in your repository. So you need a deep-enough repository to count up all the commits you care about, which is all the commits back to the root. So don't use a shallow repository.

Note that a full repository can take quite a while to set up initially, but after that, git fetch from the upstream only gets you new commits, which usually takes at most a few seconds.

Related