
Github上我们经常fork其他人的代码,然后经过一通魔改后弄出"自己"的东西。但是现在我遇到了这么一个需求,就是我已经公开了一个自己的库(暂且叫parent),然后我想基于自己开发的库再创建新的功能,但是又不想让新功能公开,一个很自然的想法是库parent保持公开,然后新创建一条分支隐藏,可惜的是github并不支持这个功能。所以一个可行的办法就是fork自己的库,但是不是直接fork,因为你也没法fork自己的库,间接实现的方法如下:
child,然后clone到本地$ git clone https://github.com/your_name/child.git注意,一个比较重要的概念是github的分支分为本地端和远端,我们先看一下两端的分支情况
git branch命令,可看到输出结果如下。本地只有一个名为master的主分支*mastergit 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)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)第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,这样可能会产生冲突,需要手动解决。这里的远端分为被克隆的parent(即upstream)和child(即origin)。
origin:git push origin mastergit push upstream masterupstream:当然,如果你不想child影响到parent,你可以在parent的settings/branches里设置Branch protection rules,勾选Require pull request reviews before merging。这样即使你不小心运行了上面的命令也不会将代码同步到upstream。
<footer style="color:white;;background-color:rgb(24,24,24);padding:10px;border-radius:10px;"><br>
<h3 style="text-align:center;color:tomato;font-size:16px;" id="autoid-2-0-0"><br>
<b>MARSGGBO</b><b style="color:white;"><span style="font-size:25px;">♥</span>原创</b>
<p>如有意合作,欢迎私戳</p>
<p>邮箱:marsggbo@foxmail.com</p>
<b style="color:white;">
2019-12-19 15:01:40
<p></p>
</b><p><b style="color:white;"></b>
</p></h3><br>
</footer>
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。