git hook

A git hook is a script that git executes before or after a relevant git event or action is triggered.

They can be used to perform actions such as:

  • Push to staging or production without leaving git
  • No need to mess with ssh or ftp
  • Prevent commits through enforcing commit policy.
  • Prevent pushes or merges that don’t conform to certain standards or meet guideline expectations.
  • Facilitate continuous deployment.

git hook 類別

  • Client side hooks
  • Server side hooks

git hook 架構

+-- git-hooks
    +-- custom-hooks
    +-- src
    |   +-- index.js
    +-- test
    |   +-- test.js
    +-- .jscsrc

客戶端 client side hooks

client side hooks 在建立 git時就會被一併建立,放置於: .git/hooks/ 目錄下:

git init
cd .git/hooks && ls

所有檔案都是以 .sample做結尾,主要是為了防止被執行,要啟動他們,只需要把.sample移除掉就可。

chmod +x .git/hooks/<insert-hook-name-here>

該目錄下的檔案,執行的先後順序為:

<pre-commit>
           |
<prepare-commit-msg>
           |
<commit-msg>
           |
<post-commit>

pre-commit

此script會在git commit之前被執行。主要可以用來確認在遞交前是否做好了各項測試。可以用:touch pre-commit && vi pre-commit 建立此檔案。此檔案必須要有執行能力:chmod + x .git/hooks/pre-commit

#!/bin/bash

echo "Can you make a commit? Well, it depends."
exit 1

Server Side Hooks

Server Side Hooks
* 執行順序:

<pre-receive>
        |
<update>
        |
<post-receive>

PRE-RECEIVE

  • This hook is triggered on the remote repository just before the pushed files are updated and can abort the receive process if it exists with a non-zero status.

UPDATE

  • The update hook is called after the pre-receive hook and functions similarly.

POST-RECEIVE

  • This hook is triggered after an update has been done on the remote repository and so cannot abort the update process. Like the post-commit client-side hook, it can be used to trigger notifications on a successful remote repository update.

參考資料