我们正在使用git存储库来存储我们的项目。我们的分支脱离了原来的分支。但是现在我们想要创建一个小的新项目来跟踪一些文档。为此,我们需要创建一个新的空分支来开始存储我们的文件,并且我希望网络上的其他用户克隆该分支。
我们怎么做呢?
我试过一些方法,但都没用。
$ mkdir proj_doc; cd proj_doc
$ git init
$ git add .
$ git commit -m 'first commit'
$ git br proj_doc
$ git co proj_doc
$ git br -d master
$ git push origin proj_doc
它似乎推了分支,但当我进行取回或拉取时,它从其他分支下载信息,然后我也从其他项目获得一些额外的文件。最好的解决办法是什么?
创建一个空的新分支,像这样:
true | git mktree | xargs git commit-tree | xargs git branch proj-doc
如果你的proji -doc文件已经在一个单独的子目录下提交,你可以这样创建新的分支:
git commit-tree thatcommit:path/to/dir | xargs git branch proj-doc
这可能比git分支——orphan更方便,如果它会让你有很多git rm和git移动要做的话。
Try
git branch --set-upstream proj-doc origin/proj-doc
看看这能不能帮你解决"多拿"的问题。另外,如果你真的只想获取一个分支,在命令行上指定它是最安全的。
正确的答案是创建一个孤儿分支。我在我的博客上详细解释了如何做到这一点。(归档链接)
...
Before starting, upgrade to the latest version of GIT. To make sure
you’re running the latest version, run
which git
If it spits out an old version, you may need to augment your PATH with
the folder containing the version you just installed.
Ok, we’re ready. After doing a cd into the folder containing your git
checkout, create an orphan branch. For this example, I’ll name the
branch “mybranch”.
git checkout --orphan mybranch
Delete everything in the orphan branch
git rm -rf .
Make some changes
vi README.txt
Add and commit the changes
git add README.txt
git commit -m "Adding readme file"
That’s it. If you run
git log
you’ll notice that the commit history starts from scratch. To switch
back to your master branch, just run
git checkout master
You can return to the orphan branch by running
git checkout mybranch
假设你有一个带有文件/目录的主分支:
> git branch
master
> ls -la # (files and dirs which you may keep in master)
.git
directory1
directory2
file_1
..
file_n
如何一步一步地创建一个空分支:
Git checkout -orphan new_branch_name
执行以下命令前请确认所在目录正确。
ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_
Git rm -rf。
触摸new_file
Git添加了new_file
Git commit -m '在新分支中添加第一个文件'
Git push origin new_branch_name
在步骤2中,我们简单地在本地删除所有文件,以避免与新分支上的文件和保留在主分支中的文件混淆。
然后,我们在步骤3中解除所有这些文件的链接。最后,第4步和之后将使用新的空分支。
一旦你完成了,你可以很容易地在你的分支之间切换:
git checkout master
git checkout new_branch
最好的解决方案是使用——orphan选项创建一个新的分支,如下所示
git checkout --orphan <branch name>
这样您就可以创建一个新分支,并直接签出到新分支。它将是一个没有父母的分支。
默认情况下——orphan选项不会删除工作目录中的文件,所以你可以通过以下方法删除工作目录中的文件:
git rm --cached -r
——orphan的具体作用:
——孤儿< new_branch >
创建一个新的孤儿分支,命名为<new_branch>,从<start_point>开始并切换到它。在这个新分支上进行的第一次提交将没有父节点,它将是一个与所有其他分支和提交完全断开的新历史的根节点。
索引和工作树被调整,就像你之前运行git checkout <start_point>一样。这允许你开始一个新的历史记录,记录一组类似于<start_point>的路径,通过简单地运行git commit -a来进行根提交。
当您希望从提交中发布树而不暴露其完整历史时,这可能很有用。您可能希望这样做来发布一个项目的开源分支,该项目的当前树是“干净的”,但其完整的历史记录包含专有的或其他阻碍的代码位。
如果你想启动一个断开连接的历史记录,记录一组完全不同于<start_point>的路径,那么你应该在创建孤分支后立即通过运行git rm -rf清除索引和工作树。从工作树的顶层。然后你就可以准备好你的新文件,重新填充工作树,从其他地方复制它们,提取一个tarball,等等。