将单个分支及其历史复制到新存储库

Copy a single branch and its history to a new repository

有没有一种简单的方法可以从存储库中复制一个分支并保留其历史记录?

我以为我在做 git 克隆时得到了它,但是当向新存储库添加源时,它说它已经有了一个,即旧存储库。

我是 git 的新手,所以请明确回答。 :-)

谢谢。

当您克隆一个存储库时,您从中克隆它的存储库的 URL 将用作远程(通常称为 "origin")。这很正常。但是,您可以拥有多个 Git 的远程存储库。 (或者您可以将遥控器 origin 更改为指向另一个位置,如果您只需要一个。)

所以我们假设 "old" 存储库位于 http://example.com/old.git and the new repository with only one branch from the old remote will be located at http://example.com/new.git。在那种情况下,过程如下:

# clone the repository into directory old
git clone http://example.com/old.git old
cd old
# checkout the branch you want to keep, in this case "my-branch"
git checkout my-branch
# create new remote for new repository
git remote add new http://example.com/new.git
# push that branch to the new repository
git push new my-branch

这假定新存储库已经存在,但是是空的。

额外奖励:如果您想知道存在哪些远程存储库,您可以使用

列出它们
git remote -v

输出类似于

origin  http://example.com/old.git (fetch)
origin  http://example.com/old.git (push)
new     http://example.com/new.git (fetch)
new     http://example.com/new.git (push)

您可以使用

删除遥控器
git remote remove <name of remote>

不过,这只会删除与远程存储库的连接。您从这些遥控器获得的任何本地分支仍将保留在您的本地存储库中。