如何从现有的提交中创建一个新分支?

how can create a new branch from already existing commits?

我有一个包含三个提交的分支。现在我想为这三个提交创建三个新分支,每个提交都应该是单独的分支,我该如何实现?

我假设您想要三个独立的分支,每个分支都有一个从原始分支获取的提交。

您可以通过创建 orphan branches, and then cherry-picking 提交来做到这一点。

例如:

git checkout --orphan branch1
git reset --hard
git cherry-pick <hash-of-commit-1>

其他两个提交依此类推。

您想按以下方式使用 git branch

git branch branch_name <sha1-of-commit>

所以既然你想从这三个提交中得到三个分支,你应该使用:

git branch branch1 <commit #1>
git branch branch2 <commit #2>
git branch branch3 <commit #3>

要查找三个提交的 SHA-1 哈希值,您可以在相关分支上键入 git log。检查日志,直到找到您要从中分支的三个提交。

关于 git 个分支机构

阅读问题和评论(来自 OP),我相信对 git 中的 的分支存在混淆。分支只是一个指向提交的小便签。分支不是git中的"heavy"对象,所以你不是真的"create new branches with those commits",说"each commit should be a different branch"也没有意义;你只需标记一个提交 "mybranch1",另一个提交 "mybranch2" 等等。命令由@TimBiegeleisen (git branch <name> <commit>) 给出。

阅读一些关于 git 如何构建其数据的入门读物可能会有所帮助。 http://gitready.com/beginner/2009/02/17/how-git-stores-your-data.html

从原始提交创建新分支,然后cherry-pick您想要的提交:

# From the master branch
git branch branch-1 HEAD~2

git checkout -b branch-2 master~3
git cherry-pick master~1

git checkout -b branch-3 master~3
git cherry-pick master