Git 防止在修改提交后推送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18588974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 16:53:23  来源:igfitidea点击:

Git prevents pushing after amending a commit

gitgit-pushgit-commitamend

提问by kiri

Usually, I just run

通常,我只是跑

git add file
git commit
git push

but if I amend the commit beforepushing it (with git commit --amend), the next push fails with

但是如果我推送之前修改提交(使用git commit --amend),下一次推送将失败

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.

How can I let git push the changes without merging branches? I only have one branch (master) and I'm the only person using this repo so why is it saying this?

如何在不合并分支的情况下让 git 推送更改?我只有一个分支 ( master) 并且我是唯一一个使用这个 repo 的人,所以为什么要这样说?

git branch -a:

git 分支 -a:

* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

EDIT: Using gitk HEAD @{u}, I see that I have 2 branches, one with the original commit and another with the amended commit.

编辑:使用gitk HEAD @{u},我看到我有 2 个分支,一个带有原始提交,另一个带有修改后的提交。

回答by Joey

This should only be the case if you're amending an already-pushed commit. Generally you should never do that as you're then modifying published history. In your case however, you should be able to get away with push -f, which will overwrite the remote commit with your amended revision.

仅当您要修改已推送的提交时才应如此。通常,您永远不应该这样做,因为您正在修改已发布的历史记录。但是,在您的情况下,您应该可以使用push -f,这将用您修改后的修订覆盖远程提交。

回答by Nils Werner

Yup, you should not do that (pushing a commit, then changing it and trying to push it again).

是的,您不应该这样做(推送提交,然后更改并尝试再次推送)。

Instead, you can roll back Git to your previous commit without changing the files, then creating a new commit:

相反,您可以在不更改文件的情况下将 Git 回滚到之前的提交,然后创建新的提交:

git reset --mixed origin/master
git add .
git commit -m "This is a new commit for what I originally planned to be an amendmend"
git push origin master

this will create a new commit with the changes you were about to amend.

这将创建一个包含您即将修改的更改的新提交。

回答by Stefano Falasca

you amended the pulled commit as in

你修改了拉取的提交

git pull origin master
git commit -a --amend -m "..."
git push

you can solve the issue by reverting the amended commit:

您可以通过恢复修改后的提交来解决问题:

git reset --mixed origin/master

and then making it again as a full fledged commit

然后再次作为一个完整的提交