Github上我們經常fork其他人的代碼,然后經過一通魔改后弄出"自己"的東西。但是現在我遇到了這么一個需求,就是我已經公開了一個自己的庫(暫且叫parent
),然后我想基於自己開發的庫再創建新的功能,但是又不想讓新功能公開,一個很自然的想法是庫parent
保持公開,然后新創建一條分支隱藏,可惜的是github並不支持這個功能。所以一個可行的辦法就是fork自己的庫,但是不是直接fork,因為你也沒法fork自己的庫,間接實現的方法如下:
1) 在github新建一個庫child
,然后clone到本地
$ git clone https://github.com/your_name/child.git
注意,一個比較重要的概念是github的分支分為本地端和遠端,我們先看一下兩端的分支情況
- 查看本地分支情況: 輸入
git branch
命令,可看到輸出結果如下。本地只有一個名為master的主分支
*master
- 查看遠端分支情況,輸入
git remote -v
命令,輸出結果如下。可以看到只有一個名為origin遠端主分支,其中fetch和push表示不同操作,前者是“拿來”意思,也就是同步到本地,后者是“推送”,即將本地代碼同步到遠端。
origin https://github.com/your_name/child_test.git (fetch)
origin https://github.com/your_name/child_test.git (push)
2) 將parent
分支加入到遠端分支
cd child
git remote add upstream https://github.com/your_name/parent.git
上面代碼的意思是給child
庫的遠端加上一個名字為upstream
的分支,該分支路徑則是你想要fork的庫的路徑。
我們可以輸入git remote -v
查看現在遠端分支的情況
origin https://github.com/your_name/child_test.git (fetch)
origin https://github.com/your_name/child_test.git (push)
upstream https://github.com/your_name/parent_test.git (fetch)
upstream https://github.com/your_name/parent_test.git (push)
3) 將遠端分支同步到本地
第2步只是遠端分支進行了fork,真正要使用代碼,我們還需要把upstream遠端分支同步到本地,方法如下:
git pull upstream master
如果你遇到了fatal: refusing to merge unrelated histories
報錯信息,可以加上--allow-unrelated-histories
,即
git pull upstream master --allow-unrelated-histories
這樣遠端parent
代碼就同步到里新創建的child
庫了。如果你想要和parent
保持一致,可以通過上面的pull
方法實現,也可以通過fetch
+merge
的方式。
簡單解釋就是:
git fetch
是將遠程主機的最新內容拉到本地,用戶在檢查了以后決定是否合並到工作本機分支中。git pull
則是將遠程主機的最新內容拉下來后直接合並,即:git pull = git fetch + git merge
,這樣可能會產生沖突,需要手動解決。
4) 將修改后的代碼同步到遠端
這里的遠端分為被克隆的parent
(即upstream
)和child
(即origin
)。
- 同步到
origin
:
git push origin master
- 同步到
upstream
:
git push upstream master
當然,如果你不想child
影響到parent
,你可以在parent
的settings/branches
里設置Branch protection rules
,勾選Require pull request reviews before merging
。這樣即使你不小心運行了上面的命令也不會將代碼同步到upstream
。