Git: How to Compress Commit History?
Using Git for version control, compressing commit history is a method to optimize project history, making the repository cleaner and easier to manage. Specifically, compressing commit history in Git typically involves using the rebase feature to interactively merge multiple commits. Below are detailed steps and examples:
Step 1: Use Interactive Rebase
First, you can use the git rebase -i command to start an interactive rebase. Here, -i stands for interactive.
For example, if you want to compress the last three commits, you can do this:
bashgit rebase -i HEAD~3
This command opens a text editor listing the most recent three commits.
Step 2: Select Commits for Squashing
In the opened text editor, you will see content similar to the following:
shellpick e3a1b35 Fixed a bug pick 7ac9a67 Updated documentation pick 4ed2dae Added a new feature
To squash these commits, change the pick command to squash or fixup. squash merges the commit into the previous one and allows you to edit the commit message; fixup also merges into the previous commit but discards the commit message of the current commit.
For example, if you want to squash the last two commits into the first one and edit the commit message, you can modify it to:
shellpick e3a1b35 Fixed a bug squash 7ac9a67 Updated documentation squash 4ed2dae Added a new feature
Step 3: Edit Commit Message
After saving and closing the editor, if you used squash, Git will prompt you to edit a new commit message that includes information from all squashed commits. You can organize this information and write a new, meaningful commit message.
Step 4: Complete the Rebase
After editing the commit message, save and close the editor. Git will automatically complete the rebase operation. If conflicts arise, resolve them manually and then use git rebase --continue to proceed with the rebase.
Using this method, you can effectively compress commit history, making the project history clearer. This is particularly useful for removing erroneous or unnecessary commits and also helps clean up personal work history before merging a branch into the main branch.