Git Squash: Streamline Commit History for Cleaner Code Management

·

2 min read

Cover Image for Git Squash: Streamline Commit History for Cleaner Code Management

After committing to a branch multiple times, the commit history can quickly become cluttered, making the branch history messy and difficult to follow. Git squash is a technique that helps avoid this clutter and streamline the commit history.

In Git, the term "squash" refers to the process of combining multiple commits into a single commit.

It's important to note that Git does not have a dedicated "git squash" command. Rather, squashing is an option available during other Git operations like interactive rebase or merge.

Advantages of using git squash:

a) Clean commit history: Squashing multiple small, incremental commits into one or a few meaningful commits creates a clean and concise commit history.

b) Improved readability: Git squash makes it easier for developers to understand the changes introduced in a branch by condensing them into more comprehensible commits.

c)Efficient code review: Reviewers can focus on reviewing the final changes instead of going through numerous small commits, saving time and improving efficiency.

To perform git squash, follow these steps:

Interactive rebase

a) Ensure you are on the desired branch by executing

git checkout <branch_name>

b) Identify the number of commits you want to squash then to view the commit history use the command

git log --oneline

c) Run the interactive rebase command with the specified number of commits. For instance, if you want to squash the last three commits, use

git rebase -i HEAD~3

which will open an interactive rebase window.

d) In the interactive rebase window, change the word "pick" to "squash" or "s" for the commits you want to squash, while leaving the word "pick" unchanged for the main commit.

e) Save and close the interactive rebase window.

f) Git will prompt you to provide a new commit message for the squashed commit. Modify the commit message if desired and save it.

g) Finally, force-push the updated branch using

git push -f

if you have already pushed the previous commits to the remote repository.

If it's your first time then use

git push --force origin <branch-name>

h) Be mindful of potential implications for the branch history if collaborating with others.

Squash and merge

When closing a Pull Request, it is common to utilize the "Squash and merge" option, especially on popular code hosting platforms like GitHub, GitLab, or Bitbucket. When merging the pull request by selecting the "Squash and merge" option git squash can also be done.

Conclusion

I hope this quick article has provided an overview of the git squash.

Here are some additional resources to explore git squash further.

https://www.freecodecamp.org/news/git-squash-commits/

https://www.javatpoint.com/git-squash

https://stackoverflow.com/questions/5189560/how-do-i-squash-my-last-n-commits-together