How do I get the Git commit count?

2019-01-01 09:22发布

I'd like to get the number of commits of my Git repository, a bit like SVN revision numbers.

The goal is to use it as a unique, incrementing build number.

I currently do like that, on Unix/Cygwin/msysGit:

git log --pretty=format:'' | wc -l

But I feel it's a bit of a hack.

Is there a better way to do that? It would be cool if I actually didn't need wc or even Git, so it could work on a bare Windows. Just read a file or a directory structure...

20条回答
梦寄多情
2楼-- · 2019-01-01 09:55

If you’re looking for a unique and still quite readable identifier for commits, git describe might be just the thing for you.

查看更多
君临天下
3楼-- · 2019-01-01 09:57

git rev-parse --short HEAD

查看更多
看风景的人
4楼-- · 2019-01-01 09:58

Using Bash syntax,

$(git rev-list --count HEAD)

looks fine for purely linear history. If you also want to sometimes have “numbers” from branches (based off master), consider:

$(git rev-list --count $(git merge-base master HEAD)).$(git rev-list --count ^master HEAD)

When run from a checkout of master, you get simply 1234.0 or the like. When run from a checkout of a branch you will get something like 1234.13, if there have been 13 commits made on that branch. Obviously this is useful only insofar as you are basing at most one branch off a given master revision.

--first-parent could be added to the micro number to suppress some commits arising only from merging other branches, though it is probably unnecessary.

查看更多
泪湿衣
5楼-- · 2019-01-01 10:02

To get it into a variable, the easiest way is:

export GIT_REV_COUNT=`git rev-list --all --count`
查看更多
梦寄多情
6楼-- · 2019-01-01 10:03

If you're just using one branch, such as master, I think this would work great:

git rev-list --full-history --all | wc -l

This will only output a number. You can alias it to something like

git revno

to make things really convenient. To do so, edit your .git/config file and add this in:

[alias]
    revno = "!git rev-list --full-history --all | wc -l"

This will not work on Windows. I do not know the equivalent of "wc" for that OS, but writing a Python script to do the counting for you would be a multi-platform solution.

查看更多
不再属于我。
7楼-- · 2019-01-01 10:05

git rev-list HEAD --count

git rev-list

git rev-list <commit> : List commits that are reachable by following the parent links from the given commit (in this case, HEAD).

--count : Print a number stating how many commits would have been listed, and suppress all other output.

查看更多
登录 后发表回答