当git提交到了错误的分支
在 2024-02-06 发布于 工具 分类
大家应该都有过这样的经历:你写了一堆代码,提交的时候却忘了创建新分支,导致直接提交到了master分支上。而你们公司的要求是必须提交到新分支上。下面的办法可已将提交到一个分支上的提交“移动”到另一个分支上。
- 首先确定想把多少个提交移动到新分支
git log
你将看到类似这样的内容:
commit 5576dbf62182ac1d263e9777e31ff7f35ac6eee3 (HEAD -> master)
Author: Tyler <tyler@email.com>
Date: Fri Nov 8 12:04:42 2019 -0800
Another commit to move
commit edec499e8c85adf8c6fd79bc1b6993bfb233a5a0
Author: Tyler <tyler@email.com>
Date: Fri Nov 8 12:04:29 2019 -0800
One commit to move
commit 896cfcd0ae55d95fa81915a60460948b40fa55fa (origin/master, origin/HEAD)
Author: Zach Levine <zach@email.com>
Date: Thu Nov 7 10:40:13 2019 -0500
Awesome code added to the repository.
从这可以看到,你在master分支上有两个未push的提交。下面的步骤里我们假定这两个提交需要移动。
- 创建新分支
git branch newbranch
这将创建一个新分支,其中包含了你在原分支的所有提交。我们只需要在下面的步骤将原分支向后退若干个提交。最新的提交就只在新分支上了。
- 将当前分支向后移动若干个提交
git reset --keep HEAD~2
- checkout到新分支
git checkout newbranch
这样最后的两个提交就移动到了新的分支