git amend scenerios

Sometimes we need to change the commit message of already committed/committed-pushed files. See below some of the scenarios might arise..

Scenerio 1-> Committed but not pushed

$ git commit --amend

This will open an editor with the commit message. If you are using vi editor edit the commit message and save using !wq: Check with $git log if the message has been amended correctly.

Scenerio 2-> Already pushed + most recent commit

It might be the case that if a user has already pushed the changes to git central repository, in this type of scenario we need to first amend the most recent local commit and afterward apply –force push which will forcefully push the changes to the server. In this process, one thing to keep in mind is that if in between any other user who has already synced local copy with the central repository needs to re-pull.

 $ git commit --amend
Edit the message in vi and save and exit
$ git push origin <branch_name> --force


Scenerio 3-> Not pushed + old commit

$ git rebase -i HEAD~X

where X is the number of commits to go back then move to the line of your commit, change pick and edit then change your commit message

$ git commit --amend 

Finish the rebase with:

$ git rebase --continue

Rebase opened your history and let you pick what to change. With edit, you tell that you want to change the message. Git moves you to a new branch to let you –amend the message. git rebase — continue puts you back in your previous branch with the message changes.

alternatively, you can choose reword instead of edit when rebasing to change the commit directly. Then you can skip the amend and rebase continue. You may check this link from git book for more on this.

Scenerio 4-> Already pushed + old commit
Edit your message with the same 3 steps process as menined in scenerios 2 ( rebase –i, commit –amend, rebase –continue). Then force push the commit

$git push <branch_name> master --force

But! please remember re-pushing your commit after changing it will very likely to prevent others to sync with the repo, if they already pulled a copy. You should first check with them.


References:
https://gist.github.com/nepsilon/156387acf9e1e72d48fa35c4fabef0b4

https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.