Git 佈署小小小小筆記

SDpower 提到了 git checkout -f 的用意。其實跟 git checkout HEAD . 的作用一樣,強制將最後一次做的修改(Commit)給 Pull 下來更新,如果遇到本地端的更新,則會將現有修改全部恢復成上次的修改(Commit),然後將檔案全部抓下來,既有(非 git 系統內的檔案,如系統產生的 log)不會受到影響。

這樣做的好處是:

  • 我們已經將 worktree 指向特定目錄,這個目錄也許是網站的 Document Root 之類的。
  • 不希望有人直接去更動主機端的檔案,強制以 Git 更新為最主要的目標。
  • Git 更新之後,Staging 這類測試用主機,檔案會直接在 Web Server 上面生效。
  • 可以利用 Shell Script 補完對 Production 主機的佈署。
  • 其實也是因為我比較喜歡寫 shell-script 的關係(被揍飛

首先是我們找一台機器來當 Git Server!我這邊用 192.168.2.100 來當例子。

$ cd ~
$ mkdir git
$ cd git/
$ mkdir staging.git
$ cd staging.git/
$ git init --bare
$ git --bare update-server-info
$ git config core.worktree /home/hinablue/staging
$ git config core.bare false
$ git config receive.denycurrentbranch ignore
$ echo "git checkout -f" >> hooks/post-receive
$ chmod +x hooks/post-receive
$ chmod g+rwx -R .

然後我們從本地端來 Clone 這個 Git!

git clone hinablue@192.168.2.100:/home/hinablue/git/staging.git
$ cd staging/
$ git add .
$ git commit -m "commit 當然要用中文"
$ git push origin master

伺服器端的 core.worktree 就是我們 Commit 上去之後,利用 post-receive 來執行 git checkout -f 的指令。所以,我們在本地端 Push 資料上去的時候,他就會自動 Pull 一份到我們設定的 worktree 裡面。如果你有開 branch 的話,再你還沒有合併到 master 之前,你在 branch 的 Push 並不會影響到遠端上面的資料的。

當然,post-receive 是可以自己修改的。你可以利用你習慣的 shell-script 來去對這個指令檔案做其他的動作。不過,執行 post-receive 這個指令的目錄,以這個例子來說,他是在 /home/hinablue/git/staging.git/ 底下,所以,當你要對其他的資料夾做動作的時候,請格外小心。

老實說,對於 Git 的 Hook 著墨的文章不多,不知道是不是因為他是 shell-script 的關係?

暫時先這樣,改天有更多的心得或是地雷再來分享!

關於 Git 文章可參考:

Debian Linux 架設使用 SSH 存取 的 Git Server

ihower 系列文章,必看!

Pro Git(英文書)

Deploying a Site With Git Hooks

Deploying Websites With a Tiny Git Hook