When using git, it’s easy to become addicted to committing every small improvement. The code finally compiles. Commit! The color is finally just right in that table cell. Commit! The parameters on that method call to perform that database query (finally) work. Commit! If you are like me, there is sense of satisfaction when completing a task and committing code. Like toasting a job well done.
But, sometimes I really don’t want to push five (or more) trivial commits to the public repository because the team usually wants to see a larger chunk of work. Or perhaps I simply want to condense my local commits for my own reasons.
Question: How can I replace the previous five minor local commits with a single, meaningful commit prior to pushing to GitHub?
Answer: The answer is shockingly simple. Two short commands will accomplish the task.
The “git reset –soft xxxxxx” command will not touch your working tree but resets the branch pointer to a previous commit. After the reset, a new commit can be made which effectively removes the minor commits.
This step is not strictly required but recommended.
Notice that branch TK-32748 has five minor commits since origin/TK-32748 that I want to replace with a single new commit.
The actual commit can also be a relative commit (e.g., HEAD\^\^\^\^\^)
Notice HEAD and TK-32748 now point to 4286f89 (the commit just prior to my minor commits). A key point is that your working tree still contains EXACTLY the same contents you started with, ready for you to commit into a new and summarized commit. (I placed a tag ‘V20’ in case I need to go back to the commit.)
Two simple commands collapse many minor commits into a single meaningful one. As far as branch TK-32748 is concerned, the minor commits never happened!
CAUTION: As a final note, the usual warnings for rewriting history apply – do not push the branch if you have already pushed deleted commits into a public repository.
Harris Kirk
Development and Operations Software Engineer