0%

git subtree

在網路上搜尋了一下,發現這功能真是好用。
原先的git submodule缺點不少,一堆批評的聲音。因此之後就有git subtree的誕生,,官方也建議用git subtree解決大部分的問題。

主要應用在兩個場景

引用另外一個Repository的管理

假設在我們的Repository當中,需要引用另一個Repository(如Application需要3rd party library)的內容時,盡其希望其Repository能夠跟著更新,一旦我們對其修改時,也能擁有修改和提交的權利。

第一步: 建立目前Repository跟Sub Repository的關聯性

1
2
$ git remote -f add <name of sub_repo> <address of sub_repo>
$ git subtree add --prefix=<name of sub_directory> <name of sub_repo> <branch> --squash

第一個指令加上-f是建立關聯之後再度進行fetch作業。
而第二個指令加上--squash是要把Sub Repository的history合併成一個。
例如

1
2
$ git remote add -f ai https://github.com/aoxu/ai.git  
$ git subtree add --prefix=ai ai master --squash

第二步: 更新Sub Directory

一旦Sub Repository有人更改之後,我們希望把修改的東西合併到我們 Repository中。

1
2
$ git fetch <name of sub_repo> <branch>
$ git subtree pull --prefix=<name of sub_directory> <name of sub_repo> <branch> --squash

這就類似上面的情況了,一樣給的範例

1
2
$ git fetch ai master  
$ git subtree pull --prefix=ai ai --squash

第三步: 將修改推送到Remote Repository

Push只需要一個步驟

1
$ git subtree push --prefix=<name of sub_directory> <name of sub_repo> <branch>

同樣有個範例

1
$ git subtree push --prefix=ai ai master  

如果不用git subtree的話,也有個Subtree merge strategy見仁見智了。

參考資料:

將Sub directory拆成令外一個Repository

這剛好跟上面那個使用奇境相反,使用方式如下

第一步: 先將sub directory的資料建立new branch

1
$ git subtree split -P <sub_directory> -b <branch>

第二步: 準備new repository並且啦取原先repository的branch資訊

1
2
3
$ mkdir <new-repo> && cd <new-repo>
$ git init
$git pull <path of original repo> <name-of-new-branch>

第三步: 建立Remote Repository的關聯並推送到遠方

1
2
$ git remote add origin <git@github.com:my-user/new-repo.git>
$ git push origin -u master

參考資料: