我在远程存储库中有一个项目,与本地存储库(开发)和服务器存储库(prod)同步。我一直在做一些已经推送到远程和从服务器上拉出来的承诺更改。现在,我想撤销这些更改。因此,我可以在更改之前签出到提交,并提交新更改,但我猜再次将它们推到远程会有问题。我该怎么做,有什么建议吗?


当前回答

git revert HEAD -m 1

在上面的代码行。"最后一个参数表示"

1 -还原一次提交。 2 -返回最近两次提交。 N -返回上一个N 提交。

该命令后需要按一下才能对远程生效。您还有其他选项,例如指定要恢复的提交范围。这是选项之一。


稍后使用git commit -am "COMMIT_MESSAGE" 然后是git push或git push -f

其他回答

在这些情况下,我所做的是:

在服务器中,将光标移回上一次已知的正确提交: Git push -f origin <last_known_good_commit>:<branch_name> 在本地,执行同样的操作: Git重置——hard <last_known_good_commit> # ^^^^^^ # 可选




查看我为此目的创建的分支my_new_branch的完整示例:

$ git branch
my_new_branch

这是在myfile.py中添加了一些东西后的最近历史:

$ git log
commit 80143bcaaca77963a47c211a9cbe664d5448d546
Author: me
Date:   Wed Mar 23 12:48:03 2016 +0100

    Adding new stuff in myfile.py

commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date:   Tue Mar 18 12:46:59 2016 +0100

    Initial commit

我想摆脱上一个提交,它已经被推送了,所以我运行:

$ git push -f origin b4zad078237fa48746a4feb6517fa409f6bf238e:my_new_branch
Total 0 (delta 0), reused 0 (delta 0)
To git@github.com:me/myrepo.git
 + 80143bc...b4zad07 b4zad078237fa48746a4feb6517fa409f6bf238e -> my_new_branch (forced update)

好了!现在我看到提交时更改的文件(myfile.py)显示为“not staging for commit”:

$ git status
On branch my_new_branch
Your branch is up-to-date with 'origin/my_new_branch'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   myfile.py

no changes added to commit (use "git add" and/or "git commit -a")

因为我不想要这些改变,我只是把光标移回本地:

$ git reset --hard b4zad078237fa48746a4feb6517fa409f6bf238e
HEAD is now at b4zad07 Initial commit

所以现在HEAD在之前的提交中,在本地和远程:

$ git log
commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date:   Tue Mar 18 12:46:59 2016 +0100

    Initial commit
git revert HEAD -m 1

在上面的代码行。"最后一个参数表示"

1 -还原一次提交。 2 -返回最近两次提交。 N -返回上一个N 提交。

该命令后需要按一下才能对远程生效。您还有其他选项,例如指定要恢复的提交范围。这是选项之一。


稍后使用git commit -am "COMMIT_MESSAGE" 然后是git push或git push -f

这是我的方法:

假设分支名为develop。

# Checkout a new temp branch based on one history commit
# (command to get history commit hashes: git log --oneline)
git checkout <last_known_good_commit_hash>

# Delete the original develop branch 
git branch -D develop
# Create a new develop branch based on the temp branch
git checkout -b develop

# Force update the remote with the new branch
git push -f origin develop

重置对我来说很困难: 谢谢@Mo D Genensis和@vibs2006


git reset --hard 'your last working commit hash'

git clean -f -d

git push -f

简单方法:

git reset <commit_hash>

(您希望保留的最后一个提交的哈希值)。

您将在本地保留当前未提交的更改。

如果你想再推一次,你必须做到:

git push -f