2015年1月28日 星期三

使用git hooks管理網站

本地倉庫
$ cd ~/test/
$ mkdir website && cd website
$ git init
$ echo 'Hello, world!' > index.html
$ git add index.html
$ git commit -q -m "The humble beginnings of my web site."
註: git commit -q  是--quiet ,抑制commit 時的訊息

遠端倉庫 ( 我在同一個file system下測試,沒用ssh )
$ cd ~/test/
$ mkdir website.git && cd website.git
$ git init --bare

在website.git 資料夾下繼續操作:
$ mkdir ~/test/www.example.org
$ cat > hooks/post-receive
#!/bin/sh
GIT_WORK_TREE=/home/bear/test/www.example.org git checkout -f
$ chmod +x hooks/post-receive
註:
post- 是 "後" 的意思,遠端倉庫在收到commit後所作的動作
chmod +x 把檔案權限變成755

回到本地倉庫繼續操作
$ cd ~/test/
$ git remote add web file:///home/bear/test/website.git
$ git push web +master:refs/heads/master

簡化push的動作
$ git push --set-upstream web master #設定一次就可以了
$ git push web

檢查
在 /home/bear/test/website.git 中檢查push上來的檔案有沒有被更新

hook 有分 用戶端掛鉤 和 伺服器端掛鉤
用戶端掛鉤
位置在 ~/test/website/.git/hooks ,sample檔是bash寫的,可以用其他語言,如perl寫,只需要在第一行指定 #!/usr/bin/perl ,記得把權限改成755 ,script最後只要exit 1 就會被中止,
執行順序:
pre-commit  => commit-msg => post-commit ( 我沒測 prepare-commit-msg,但我想應該是在 pre-commit和commit-msg之間 )
以 commit-msg 為例:
commit-msg 掛鉤接收一個參數,此參數是包含最近提交資訊的暫存檔路徑( .git/COMMIT_EDITMSG )。
bash 收這個參數是 $1,perl 是 $ARGV[0]

有了這些掛鉤就能客製化開發者們在commit 時限制commit message的格式,外掛jslint檢查程式碼,檢查行尾有無空白,沒有錯誤才push到伺服器上

伺服器端掛鉤
pre-receive
post-receive # 上面的例子有用到這個
update

參考資料:
http://toroid.org/ams/git-website-howto
http://git-scm.com/book/zh-tw/v1/Git-%E5%AE%A2%E8%A3%BD%E5%8C%96-Git-Hooks #hook相關屬性

沒有留言:

張貼留言