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


当前回答

这是我的方法:

假设分支名为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

其他回答

git revert HEAD -m 1

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

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

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


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

另一种不需要恢复(undo的痕迹)的方法:

如果其他人已经推送了其他提交,就不要这样做

创建你的分支的备份,在你的分支my-branch。因此,如果出现错误,您可以重新启动进程而不会损失任何已完成的工作。

git checkout -b my-branch-temp

回到你的分行去。

git checkout my-branch

重置,放弃你的最后一次提交(撤销它):

git reset --hard HEAD^

移除远程上的分支(例如origin远程)。

git push origin :my-branch

将分支重新推到远程(没有不必要的提交)。

git push origin my-branch

完成了!

我希望这对你有所帮助!;)

假设61234是您希望保持的最后一个良好提交的sha-number。

git reset --hard 61234
git push -f

将完全删除所有错误的提交,没有任何痕迹。

注意:如果你想推送(你重置的提交)到一个特定的分支,你可以使用git push -f origin branch-name来代替。

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

在服务器中,将光标移回上一次已知的正确提交: 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重置<commit_hash>(获取<commit_hash>使用Git log——oneline)

Git恢复。将所有更改的文件恢复到yout目标提交的版本

Git push origin master——force强制推到远程主分支。但如果有人和你在同一分支工作,在使用力推时要小心