回到仓库的特定版本后提交并推送更改?

6

我们需要回到特定的提交记录。一些意外更改已经被合并到了主分支上,试图还原这些更改会导致问题进一步加剧,因此我们需要将主分支恢复到 66ada4cc61d62afc 提交记录。

根据 git revert back to certain commit

$ git reset --hard 66ada4cc61d62afc
HEAD is now at 66ada4c Updated documentation

接着,尝试提交它:

$ git add *.h *.cpp
$ git commit -m "Go back to Commit 66ada4cc61d62afc"
On branch master
Your branch is behind 'origin/master' by 16 commits, and can be fast-forwarded.
  (use "git pull" to update your local branch)

nothing to commit, working directory clean

最后:
$ git push
To https://github.com/weidai11/cryptopp.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/weidai11/cryptopp.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

现在,一切都恰到好处。我不知道为什么Git出了问题,也不知道Git在说什么。如果Git能按照指示执行就太好了。但不幸的是,Git使每个简单的任务都变得困难,并会带来不必要的痛苦和折磨。

我该如何提交并推送更改?

4个回答

9
快速解决方案: git push -f 这将强制推送并覆盖远程历史记录。但如果有其他人在使用此远程存储库:请勿这样做! 从远程存储库拉取的其他人将遇到问题,因为他们的历史记录不再是存储库历史记录的子集。大多数项目禁止强制推送。
更好的解决方案是为更改创建一个新提交。可以采用以下两种方法之一: git revert hashes 或者 git checkout oldversion .; git add/commit 这将在您的历史记录之上创建一个新的提交,描述了返回所需版本所需的更改。

1
更好的解决方案是为您的更改创建一个新的提交...... - 这就是我们正在尝试做的。我们希望下一个提交根据当前状态将事物改回原来的状态。 - jww
执行 git checkout 66ada4cc61d62afc .; git add .; git commit -m "foo" 命令。git checkout version 告诉你当前处于分离头状态,git checkout version filename 可以从历史记录中获取文件。 - Robin Roth
2
@RobinRoth git checkout <hash> . 不会删除文件。更安全的方法是 git checkout <hash> && git reset --soft master && git commit - poke

5

git reset 不能撤销您的更改。它只是回到旧状态。由于最新的提交已经在远程,而您没有进行任何本地更改,因此无法推送。

使用 git revert <hash>git revert <hash1>..<hash2>。这将创建一个新提交,撤销您指定的提交的更改。然后推送代码。


尝试了git revert,但它只能撤销在66ada4cc61d62afc之后的更改。我认为这是因为不小心推送的PR是针对库的先前状态。 - jww

-1
删除主分支本地和远程的内容。 检出好的版本。 创建新的主分支并将其推送到远程作为主分支。 不确定这是否完全符合OP的要求,但它可以工作。

-3
为了避免仅仅是将一组错误换成另一组部分解决方案,我进行了以下操作:
git clone https://github.com/weidai11/cryptopp.git cryptopp-old
git clone https://github.com/weidai11/cryptopp.git cryptopp-new

cd cryptopp-old
git checkout 66ada4cc61d62afc

cd ../cryptopp-new
cp ../cryptopp-old/*.h ../cryptopp-old/*.cpp .

git commit -am "Go back to Commit 66ada4cc61d62afc"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接