The letter A styled as Alchemists logo. lchemists
Published June 15, 2020 Updated June 15, 2020

Git Commit Squash

Demonstrates how to craft a Git commit for squashing into a previous commit.

Transcript

# Hello and welcome to the Alchemists Screencasts!
# Today, we'll learn about Git Commit Squash.

# Before starting, I strongly recommend watching these screencasts:
# - Git Rebase Abbreviations
# - Git Rebase Squash
# - Git Log Pretty
# The above will provide context to techniques used in this screencast.

# To begin, we have a Ruby script that adds two numbers:

ruby calc.rb 1 2

# Our team has requested we print mathematical calculations instead of sentences.
# No problem, let's fix the original implementation:

vi calc.rb

ruby calc.rb 1 2

# Much better.
# It's tempting to commit these changes as a separate commit and be done.
# We can do better:

gl

git show

# Notice the above commit is our original, flawed, implementation.
# Also, the commit body could be improved to explain our recent changes.
# So we need to commit our implementation changes AND update the commit body.
# Git Commit Squash is perfect for handling this situation:

git add calc.rb
git commit --squash 562137a634ec

gl

# Notice our last commit is prefixed `squash!` now.
# This commit shares the same subject as the original commit:

printf "%s\n" "Added calculator implementation"

# The "squash!" prefix is a special directive.
# This informs Git Rebase to associate "squash!" with the original commit. 🎉
# Now we can rebase and finish our work:

git rebase --interactive

gl

# During the rebase, the "squash!" and original commits were grouped together.
# ⚠️  This is only possible when AutoSquash support is enabled.
# With the rebase complete, we can confirm our changes:

ruby calc.rb 1 2

# ...and we have a descriptive commit message to better reflect our changes:

git show

# Here's what I love about this workflow:
# 1. Our implementation looks as if it was crafted perfectly the first time. 🎉
# 2. Our commit message was corrected to better reflect our implementation change. 🎉
# 3. We applied our implementation and commit body changes via a single rebase. 🎉
# 4. Future readers will have a high signal to noise.

# Enjoy!
# https://alchemists.io
# ☿ 🜔 🜍 🜂 🜃 🜁 🜄