How to retrieve the hash for the current commit in

2019-01-03 07:09发布

I would like to retain (for now) the ability to link Git changesets to workitems stored in TFS.

I already wrote a tool (using a hook from Git) in which I can inject workitemidentifiers into the message of a Git changeset.

However, I would also like to store the identifier of the Git commit (the hash) into a custom TFS workitem field. This way I can examine a workitem in TFS and see what Git changesets are associated with the workitem.

How can I easily retrieve the hash from the current commit from Git?

18条回答
等我变得足够好
2楼-- · 2019-01-03 07:59

Another one, using git log:

git log -1 --format="%H"

It's very similar to the of @outofculture though a bit shorter.

查看更多
贪生不怕死
3楼-- · 2019-01-03 08:00

Use git rev-list --max-count=1 HEAD

查看更多
叼着烟拽天下
4楼-- · 2019-01-03 08:01

Here is one-liner in Bash shell using direct read from git files:

(head=($(<.git/HEAD)); cat .git/${head[1]})

You need to run above command in your git root folder.

This method can be useful when you've repository files, but git command has been not installed.

If won't work, check in .git/refs/heads folder what kind of heads do you have present.

查看更多
叼着烟拽天下
5楼-- · 2019-01-03 08:02

If you need to store the hash in a variable during a script, you can use

last_commit=$(git rev-parse HEAD)

Or, if you only want the first 10 characters (like github.com does)

last_commit=$(git rev-parse HEAD | cut -c1-10) 
查看更多
冷血范
6楼-- · 2019-01-03 08:03
git show-ref --head --hash head

If you're going for speed though, the approach mentioned by Deestan

cat .git/refs/heads/<branch-name>

is significantly faster than any other method listed here so far.

查看更多
放荡不羁爱自由
7楼-- · 2019-01-03 08:04

To turn arbitrary extended object reference into SHA-1, use simply git-rev-parse, for example

git rev-parse HEAD

or

git rev-parse --verify HEAD

Sidenote: If you want to turn references (branches and tags) into SHA-1, there is git show-ref and git for-each-ref.

查看更多
登录 后发表回答