Quick tip for those git users that, like me, make a lots of commits in their working branch and want to keep only the last one, before send the branch to production. Yes, the idea is to use this method before send the branch to production: it is not a good idea, to change the history of a project that has many persons working on it!
It is true that, by this method, I resetted the GitHub history of some personal projects, when they were already pushed: i didn’t get any problems, because i was the only person to commit on those projects!.
Ok, the warning is done, let’s start with the trick; so, let’s think about a branch history like this:
f960ea9275d31241e9d88512c9827bee7caed7ad Work in progress – fixed big error
602558e0841ecf5ffcce9aa660c3ae057bce3517 Work in progress – second step done
6ae2bc2e2848bb00c0b31006f14ae95686a8dbc7 Work in progress – first step done
(you can check the history of your branch by the command git log; the output above is by the command git log --pretty=oneline )
So, what i usually do, that is really bad, is:
-
Make a copy of the working branch filesystem, in a safe directory. Delete, IN THE COPY, the git’s configuration subfolder, like “.git”, if there .
-
Get the ID of the first commit: that commit will became the only one commit in the branch but the files will get the changes applied by all the commits. In this case, the ID is 6ae2bc2e2848bb00c0b31006f14ae95686a8dbc7, from above.
-
Run git reset –hard 6ae2bc2e2848bb00c0b31006f14ae95686a8dbc7Where 6ae2bc2e2848bb00c0b31006f14ae95686a8dbc7 is the id of the first commit of the branch, yours will be different.PAY ATTENTION: this command will DELETE all the changes done in the commits that follow the first one. Run it only AFTER have got a copy of the filesystem, as written in the point 1.
-
Now, we got our branch how it was at the first commit: some files are in their old version, some other are missed, some other are back! No worries; at the point 1, you did a copy of your branch filesystem: replace your current working branch filesystem with the one you have saved, so your working branch filesystem will be the one you saved at the point 1. Doing that, you will rewrite your current files (from the first commit) with the latest version of them (from the commits we did deleted in the previous point).
-
Now you have got your working branch with one commit only but the files are like they were after all the commits (that were deleted in the point 3) . What we want now is commit all the changes, keeping the commit we have already got and changing its message; we can do that by the --amend option of the git commit command:
git add **
git commit -m “My new message” --amend
Now, the files in your working branch should be at their last version; check again your branch history and it should be like that:
f960ea9275d31241e9d88512c9827bee7caed7ad My new message
That is it, we got all the changes and one commit with the specified message!
I hope it is helpful and thanks for reading!