[參考文章] 使用 Git 做為網站開發版本控管工具

小蛙最近在找一個 website 開發上的解決方案,發現下面這篇文章可以符合小蛙的要求,本文主用小蛙自己的理解”記錄”下來。【A web-focused Git workflow @ joe maller.com 】

使用 Git 做為版本控管非常好用,網路上有很多 Git 教學文:
【Git and Github 演講投影片(2011) @ ihower { blogging }】
【Git 教學(1) : Git 的基本使用 @ 好麻煩部落格】
【Git 初學筆記 – 指令操作教學 @ Tsung’s Blog】

這篇文章參考自【A web-focused Git workflow @ joe maller.com 】,以下文章指令輸入的部份源自於原始網頁,說明的部分是小蛙破英文翻過來的(只挑部份,沒有逐字翻),連結到原始作者網頁可看到更多資訊。

這邊原作者把架構拉開分成 3 種身份(點回作者網站可以看到架構圖):Clones(副本)Hub(匯整)Prime(網站)

大致上的流程為:所有開發者從 Hub clone 一份下來開發,最後 push 回 Hub,再由 Hub 中的 hook 進入 Prime 的目錄下執行 pull,當 Prime 有 commit 動作時,也透過 hook 將變動 push 到 Hub 以維持兩個 repository 的一致性。

Hub: bare repository,其他開發者只能從這邊 clone 資料。

Prime: standard repository,網站的目錄。

安裝並設定 Git

git config --global user.name "Joe, working on the server"

在網站目錄下初始化一個新的 Git repository (Prime)

cd ~/www
git init
git add .
git commit -m"initial import of pre-existing web files"

在網站目錄之外的地方建立一個 bare repository (Hub)

cd; mkdir site_hub.git; cd site_hub.git
git --bare init
Initialized empty Git repository in /home/joe/site_hub.git

從 Prime 目錄下,把 Hub 加入到 remote 中,並且把 Prime 上的 master push 到 Hub 上

cd ~/www
git remote add hub ~/site_hub.git
git remote show hub
* remote hub
  URL: /home/joe/site_hub.git
git push hub master

為了讓 hub 跟 prime 緊密連接在一起,且不影響到工作目錄結構,這邊作者在 Hub repository 上設定 post-update (參考資料2),當 Hub 接收到更新(git push)時,便會切換到網站目錄(prime)下的 repository 執行 git pull 的動作

#!/bin/sh
echo
echo "**** Pulling changes into Prime [Hub's post-update hook]"
echo
cd $HOME/www || exit
unset GIT_DIR
git pull hub master
exec git-update-server-info

在 Prime repository 中加入 post-commit (參考資料2),為了維持 hub 跟 prime 雙向一致,如果真的 Prime 被手動修改了,也可以立即將這個變動發送到 Hub 上,讓 Hub 知道這些變動,避免 conflict

#!/bin/sh
echo
echo "**** pushing changes to Hub [Prime's post-commit hook]"
echo
git push hub

有一些情況下 Prime 跟 Hub 會發生不一致的情況,作者提到如果衝突發生時,最好的做法是先把目前發生問題的 Prime 的狀態 push 到 Hub 的 “fixme” 分支,如此一來其他的 clones 就可以把有問題的分支 pull 下來,處理完成後再 merge,以免因為 Git 的衝突標示使得網站無法正常運作

git push hub master:refs/heads/fixme

由於 Prime 的 .git 資料夾在網站的根目錄可能會有安全性的問題,使用 Apache 的話可以透過以下方式禁止 .git 被存取

# deny access to the top-level git repository:
RewriteEngine On
RewriteRule \.git - [F,L]

如果看到以下錯誤,就把 export PATH=${PATH}:~/bin 加入到 Server 上的 .bashrc 中。

git-receive-pack: command not found
fatal: The remote end hung up unexpectedly

參考資料

  1. A web-focused Git workflow @ joe maller.com
    http://joemaller.com/990/a-web-focused-git-workflow/
  2. Git Hooks @ Git Book 中文版
    http://gitbook.liuhui998.com/5_8.html
  3. Git @ 維基百科,自由的百科全書
    http://zh.wikipedia.org/wiki/Git
  4. Git and Github 演講投影片(2011) @ ihower { blogging }
    http://ihower.tw/blog/archives/5391/
  5. Git 教學(1) : Git 的基本使用 @ 好麻煩部落格
    http://gogojimmy.net/2012/01/17/how-to-use-git-1-git-basic/
  6. Git 初學筆記 – 指令操作教學 @ Tsung’s Blog
    http://blog.longwin.com.tw/2009/05/git-learn-initial-command-2009/

Git 系列文章:

    發佈留言

    發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

    這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料