开发者

Use git rebase to retroactively make commits land on a different branch?

I have some commits:

 - 1 - 2 - 3 - 4 - 5 (HEAD, master)

Afterwards I notice Commits 2 & 3 really should have gone on their own branch. They are completely independent of commits 4 and 5 Can I use git rebase to make?

 - 1 - 4 - 5 (HEAD, master)
    \
     2 - 3 (TestBranch)

And most importantly, will the SHA1s for Commit 2开发者_JAVA技巧 and Commit 3 stay the same as they were before the rebase?


First, note that your desired TestBranch points simply to the current commit 3; you don't have to do anything but git branch TestBranch <commit 3> to accomplish that. Remember, branches are just pointers to commits. This should answer your question about the SHA1s of commits 2 and 3. You haven't changed those commits at all, so their SHA1s are of course the same.

To get your current branch (master) where you want it (commits 1, 4, 5), you will indeed rebase. This is a very simple case for its interactive mode. First, run:

git rebase -i <commit 1> master     # -i is a synonym for --interactive

Git will launch your editor, and show you all of the commits since commit 1 on your master branch (2,3,4,5), along with some hints about what to do. You just need to delete the lines for commits 2 and 3, then save and quit. It will then apply what's left (4 and 5), leaving you with what you want. Of course, if commits 4 and 5 depended on commit 2 or 3, you're going to get merge conflicts when git tries to apply their patches during the rebase.

Note that this will change the SHA1s of commits 4 and 5, since the SHA1 of a commit depends on its parent. This will mess with anyone who's pulled that branch. (You have been warned.) Your actual final result would more accurately be described like this:

- 1 - 4' - 5' (HEAD, master)
   \
    2 - 3 (TestBranch)

Commits 4' and 5' have the same diffs as commits 4 and 5, but have different parents, so they are different commits.


If you check out 3, you can then create a new branch TestBranch at that point, and obtain your desired branch.

Then you can go back to branch master, and rebase it interactively with git rebase -i HEAD~6, deleting 2 and 3 by removing their lines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜