2015-02-26

Tags: bitbucket , git , github

執行 "git clone" 無法將 github 各別 project 的所有 remote branch 都在 local repository 產生一份,只會在 local 產生 master branch。這時如果要將 local repository push 到(或說是搬到) new remote repository 會發生很大的問題。當你在 local repository 執行完 "git push --all" 後會發現 remote repository 只存在 master branch,其它 branch 不會出現在裡面。

當然!你可以在執行完 "git clone" 後,接著執行 "git checkout" 將 remote branch 在 local repository 裡手動一個個建出來。不過這種傻事還是少幹的好,如果 remote branch 有好儿十個,手工建立對應的 local branch 可能會讓你哭爹喴娘。這時當然要用有效率的招式才行!!!

先寫出備份 github project 專用的備份 script。我把它命名為 github_project_backup.sh

#github_project_backup.sh
#!/bin/sh

#執行前要先修改這裡,設定你的 github id
github_user_id=my_github_id

#執行前要先修改這裡,設定你的 github password
github_user_pwd=my_github_pwd

#執行這個 bash 時,在 console 要輸入的 github project name
read -p "input the name of github project : " github_project_name

#在 local 端產生 bare repository,並將 remote 端的每個 branch 都在 local 端產生一份
#
# --mirror 參數的官方說明如下
# Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only
# maps local branches of the source to local branches of the target, it maps all refs (including
# remote-tracking branches, notes etc.) and sets up a refspec configuration such that all these refs
# are overwritten by a git remote update in the target repository.
#
git clone --mirror https://${github_user_id}:${github_user_pwd}@github.com/${github_user_id}/${github_project_name}.git

cd ${github_project_name}.git

#因為 remote repository 在你備份到 local 端之後可能會刪除,所以先把 remote 來源刪掉
git remote rm origin

cd ..
進行備份,流程像下述這樣
  1. remote repository 有二個 branch、二個 tag
  2. 輸入 github 裡的 project name
  3. github_project_backup.bash 執行完畢後,產生 local bare repository,而且裡面有二個 local branch、二個 local tag
如果只打算把 github 的 project 在刪除前先備份到本地端後再刪除,到這步驟就算完成了。之後可以視需求再把備分下來的 local bare repository 進行 zip 或是 tgz 後丟到雲端(e.g. AWS S3,dropbox...etc)進行封存。

如果是打算把 local repository push 到(或說是搬到) new remote repository,接下來要執行下列指令。
cd /path/to/my_local_repository
git remote add origin https://my_new_remote_repository
git push -u origin --all #pushes up the repo and its refs for the first time
git push -u origin --tags #pushes up any tags
接續的搬移流程像下述這樣
  1. new remote repository 指到 bitbucket
  2. 搬完後 bitbucket 裡的 remote repository 有二個 branch、二個 tag,跟當初放在 github 裡的一樣
至此就完成了從 github 搬到 bitbucket 的動作。

你說何時有機會用到這篇文章的招式?如果你在 github 上面開了太多 private repository,超過單一付費帳號許可的最大上限(目前 github 最多只能開 50 個 private repository),這招就用的上了...XDDD