如何在git中修复错误的合并?

时间:2017-05-31 11:35:05

标签: git

错误合并后,最后一天的所有代码更改都被覆盖。因为没有注意到,所以在错误的合并之上进行了新的提交。我怎样才能回到某个提交然后添加错误合并后提交的提交?

git reset or git revert ?

3 个答案:

答案 0 :(得分:1)

在你的情况下,它应该足够:

  • 再次合并正确的分支与您缺少的更改
  • 还原合并提交(并且只进行合并提交)然后合并应该首先合并的当前分支

另一方面,如果由于某些恢复过去的提交而丢失了一些提交,则可能必须恢复这些恢复提交。

git reset只有在你想要强制某种状态并将其强行推送到遥控器上时才有意义,这可能会导致它自身的麻烦。在那里仔细对待,但根据存储库的状态,它可能是有道理的。

答案 1 :(得分:1)

您可以重写历史记录:

git checkout master  // switch to master
git checkout -b fix_it  // create a fix_it branch, and switch to it
git rebase -i <hash_right_before_bad_commit> // cherry-pick all the good commits - leave out the bad one

如果fix_it分支看起来不错,那么有时间重置master以使其指向fix_it:

git checkout master
git branch old_master // create an old_master branch in case you want to rollback
git reset fix_it  // now master has the new fixed history (without the bad commit)

// double-check your branches and make sure everything looks ok (and the bad commit is gone from your history)
git log --graph --all --oneline --decorate-short

// if everything looks good, push the changes to your remote repository
git push origin master --force // you'll need to force it since you've re-written history

// clean up the tmp branches
git branch -D fix_it, old_master

// inform your team members to force get master (or just to be safe, just re-clone repository).

答案 2 :(得分:1)

显示当前状态

您可以通过命令查看所有分支引用:

git branch -a

你可以看到这样的提交历史命令:

git log --graph --decorate --oneline --all

原始状态

通常,您有本地和原产地的分支参考。您刚刚通过合并操作修改了本地引用。

合并前有

eb686c4 (HEAD -> master, origin/master) some work 1
22abb23 (HEAD -> fix, origin/fix) some work 2

新州

合并后你有

aa183c1 (HEAD -> master) some work 1
bb426c2 some work 2
cc686c4 (origin/master) some work 1
ddabb23 (HEAD -> fix, origin/fix) some work 2

回滚到原点

因此,您可以通过命令

重置分支将分支回滚到previous
# here you are at master (HEAD -> master)
git reset --hard origin/master

# or if you are not at master branch
git branch -f master origin/master

回滚到初步标记状态

创建临时分支(我将分支称为m)更好:

# create branch m to ref to same commit as current branch (master)
git branch m master
# do merge or rebase
git merge ...

现在,如果您遇到一些问题,可以像创建分支m时那样重新掌握:

# here you are at master (HEAD -> master)
git reset --hard m

# or if you are not at master branch
git branch -f master m