How can I populate the Git commit ID into a file when I commit?

前端 未结 9 1481
生来不讨喜
生来不讨喜 2020-12-02 12:45

I would like to create Git hook(s) that will populate the commit id of the commit I am about to make into a file (basically variable substitution) in my source code. Is this

9条回答
  •  庸人自扰
    2020-12-02 12:51

    You can do this with the post-commit hook. Here's an excerpt from the git-scm website

    After the entire commit process is completed, the post-commit hook runs. It doesn’t take any parameters, but you can easily get the last commit by running git log -1 HEAD. Generally, this script is used for notification or something similar.

    It would be a case of getting the output of git log -1 HEAD, then using a tool like sed to replace variables in your file. However, this modifies your working directory, and unless you're going to throw those changes away then you'd end up with a permanently modified working directory.

    If you just want to use the current commit hash in a variable somewhere in your code, you could just execute git log -1 HEAD or cat .git/HEAD and store the output in your variable

    If you only want the id (hash) like in the question title, you can use the --format flag. git log -1 HEAD --format=%H

提交回复
热议问题