简体   繁体   中英

“amend” previous commit and edit the message

Let say that I want to change HEAD~2 by my current last commit "HEAD" without the change made by HEAD~. Moreover, I'd like to edit the message from HEAD~2 and not overwrite it (just few changes should be done on the message). I found that way : this is my current git log : 在此处输入图片说明

Then I did this following command :

git reset --mixed Head~3
git add new_file.cpp
git commit -m "Erased previous new_file.cpp by current new_file"
git add other_file.cpp
git commit -m "Added other_file.cpp"

So now I get this :

在此处输入图片说明

As you can see, I have rewrite all my commit to make it clean. And as I am quite newbie on reset... it can be a bit dirty.

Could it be possible to get this cleaner just by "editting" the commits ? For instance I'd like to edit the previous message from the first commit and keep the message of the second intact.

Moreover, the way I did the modification let me think the previous commit are still present and must pollute the repository : will they be erased or stay there foreever ?

PS : the GitHub repository (the reflog is quite horrible as I made some command mistake before finding the right command)

There is no possibility to change commit message without changing (at least SHA) of all its descendants. However if you still want to do so (for example you made typo earlier and you still haven't published your commit) then you can do:

git rebase --interactive HEAD~2

And then change pick at the beginning of the line with your commit to reword . It will do all git checkout / git commit --amend / git rebase magic for you.

If you want to learn more:

Moreover, the way I did the modification let me think the previous commit are still present and must pollute the repository : will they be erased or stay there foreever ?

They will eventually be garbage collected. But you should not think of unreachable commits as a problem, it's perfectly normal to have plenty of those, as there are some after many operations like rebase or reset .

Speaking of rebase : As @TimBiregeleisen mentioned, I think an interactive rebase would be the cleaner solution here: git rebase -i HEAD~2 lets you revise the last two commits. You can choose to rewrite the commit message, edit the whole commit, squash several commits into one and other things; there is plenty of documentation out there ( here or here for example).

Of course, an interactive rebase creates completely new and shiny commits and leaves the old ones dangling, but, as mentioned above, that's no problem as long as you did not push those old commits and someone else started working on top of them .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM