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

前端 未结 9 1458
生来不讨喜
生来不讨喜 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:50

    I was looking for something similar, in that I wanted a unique variable that I could add to the end of resource files (like CSS/JS) in our front end, which would allow us to set very long cache times to reduce bandwidth and increase performance, but easily force them to be reloaded after any commit. Essentially file versioning but totally automated. I didn't care that it was the MOST recent, as long as it was unique, automated, and consistent across all of our app servers.

    Our deployment script just uses 'git clone' to pull down a copy of the most recent code into our app servers, but we restrict access via .htaccess to those files and directories.

    The /.git/ directory contains a file called ORIG_HEAD which is updated after any merge (or any other dangerous operation) with the Commit ID of it's predecessor. Since we use git flow, this is perfect because it updates every time we push either a release or a fix to the master branch and deploy.

    You can do this I'm assuming in any scripting language but in our case, PHP, I did it like this...

    define("MY_VERSION",substr(file_get_contents(realpath(__DIR__.'/../.git/ORIG_HEAD')),0,3));
    

    Your path would obviously have to be tweaked for your own purposes, but this results in a 3 char unique enough id for our purposes that gets appended to the end of our resource URL's now.

    Hope that helps someone in the same situation.

提交回复
热议问题