Accidentally pushed commit: change git commit message

In my local repo I have one commit with an incorrect commit message.

I've already published the incorrect commit message with git push .

Now the remote repo (which is GitHub-hosted) has the incorrect commit message, too.

I've already tried git commit --amend , but found that it will not work for me in this situation because I've made additional commits since the incorrect one.

How would you fix this situation?


Easiest solution ( but please read this whole answer before doing this ):

  • git rebase -i <hash-of-commit-preceding-the-incorrect-one>
  • In the editor that opens, change pick to reword on the line for the incorrect commit.
  • Save the file and close the editor.
  • The editor will open again with the incorrect commit message. Fix it.
  • Save the file and close the editor.
  • git push --force to update GitHub.
  • This will mean you will be publishing a modified version of a previously published repository. If anyone pulled or fetched from your repo between when you made the mistake with the incorrect commit message, and when you fixed it, then they will experience some difficulties later. So be sure you can accept this consequence before trying this.


    Rather than go the whole rebase route for one commit:

    git reset --soft head~
    git commit -m "The message you wanted to use"
    git push -f
    

    You can see the options in the git-reset manpage.

    For a project that only you are working on, the changed history shouldn't be a problem.


    If you have to change an old commit message over multiple branches (ie, the commit with the erroneous message is present in multiple branches) you might want to use

    git filter-branch -f --msg-filter 'sed "s/<old message>/<new message>/g"' -- --all
    

    to replace the commit message.

    Git will create a temporary directory for rewriting and additionally backup old references in refs/original/.

    -f will enforce the execution of the operation. This is necessary if the the temporary directory is already present or if there are already references stored under refs/original. If that is not the case, you can drop this flag.

    -- separates filter-branch options from revision options

    --all will make sure, that all branches and tags are rewritten.

    Due to the backup of your old references, you can easily go back to the state before executing the command.

    Say, you want to recover your master and access it in branch old_master:

    git checkout -b old_master refs/original/refs/heads/master
    

    After you are satisfied with your changes use git push -f to push the changes to your public repo.

    Note that you should inform your collaborators about this since all the hashes of the commits starting with the first modified one have been changed.

    链接地址: http://www.djcxy.com/p/48926.html

    上一篇: 重做之后,Git提交在同一分支中被复制

    下一篇: 意外推送提交:更改git提交消息