我有一个Git存储库,看起来像这样:

A <- B <- C <- D <- HEAD

我希望分支的头部指向A,即,我希望B、C、D和head消失,我希望头部与A同义。

听起来我可以尝试重新设置基础(不适用,因为我已经在两者之间进行了更改),也可以恢复。但如何恢复多次提交?我一次回复一个吗?订单重要吗?


当前回答

如果你

合并提交和您无法恢复,并且你不介意粉碎你要还原的历史,

那么你可以

git reset --soft HEAD~(number of commits you'd like to revert)
git commit -m "The stuff you didn't like."
git log
# copy the hash of your last commit
git revert <hash of your last (squashed) commit>

然后,当您想要推送更改时,请记住使用-f标志,因为您修改了历史记录

git push <your fork> <your branch> -f

其他回答

如果你

合并提交和您无法恢复,并且你不介意粉碎你要还原的历史,

那么你可以

git reset --soft HEAD~(number of commits you'd like to revert)
git commit -m "The stuff you didn't like."
git log
# copy the hash of your last commit
git revert <hash of your last (squashed) commit>

然后,当您想要推送更改时,请记住使用-f标志,因为您修改了历史记录

git push <your fork> <your branch> -f

与Jakub的回答类似,这允许您轻松选择要还原的连续提交。

# Revert all commits from and including B to HEAD, inclusively
git revert --no-commit B^..HEAD
git commit -m 'message'

使用Git还原

也可以使用restore命令:

A <- B <- C <- D <- HEAD

假设你希望HEAD看起来和A完全一样,确保你已经找到了最新的主人。然后剪一根新树枝。

git switch -c feature/flux-capacitor  # synonymous with checkout -b
git restore --source A .
git add .
git commit
git push

restore命令将所有内容(.)更改为--source提交时的内容。然后将其提交给本地分支,并将其推送到源。然后,您可以对其进行公关。

这样做的好处是不会改变其他人可能以其为基础的任何历史。它也为未来的人们留下了有用的历史。

文档:git restore

首先确保您的工作副本未被修改。

然后:

git diff --binary HEAD commit_sha_you_want_to_revert_to | git apply

然后就承诺吧。不要忘记记录还原的原因。

我很沮丧,这个问题无法得到回答。其他所有问题都与如何正确还原和保存历史有关。这个问题说:“我希望分支的头部指向A,即我希望B、C、D和head消失,我希望头部与A同义。”

git checkout <branch_name>
git reset --hard <commit Hash for A>
git push -f

我在阅读Jakub的帖子时学到了很多东西,但公司里的一些人(可以在没有Pull Request的情况下推送到我们的“测试”分支)推送了五次错误的提交,试图修复他在五次提交之前犯的错误。不仅如此,还接受了一到两个拉取请求,但现在情况很糟糕。所以忘掉它吧;我找到了最后一个好的提交(abc1234),并运行了基本脚本:

git checkout testing
git reset --hard abc1234
git push -f

我告诉在这个仓库工作的其他五个人,他们最好记录下过去几个小时的变化,并从最新的测试中删除/重新广播。故事结束。