Staging Partial File Changes
In this lesson, you will learn how to selectively stage only specific parts of a file, ensuring your commit history remains clean, logical, and focused.
The Problem with "All-or-Nothing"
Up until now, you have likely been using git add <filename> to stage every change made to a file. However, imagine you are working on a single file where you fixed a critical bug and started writing a new, unfinished feature. If you run git add, both the bug fix and the incomplete code get bundled into the same snapshot. This makes your commit history messy and difficult to revert if that new feature introduces a bug.
Introducing "Patch Mode"
Git allows you to break a file down into "hunks"—small, logical blocks of additions and deletions. Instead of staging the entire file, you can tell Git to interactively ask you which sections of the file to include in the next commit.
You trigger this by using the -p (patch) flag:
git add -p filename.txt
Once you run this, Git will pause and present you with a chunk of your code. It will ask: Stage this hunk [y,n,q,a,d,s,...]?
- y (yes): Stage this specific hunk.
- n (no): Skip this hunk; keep it in your working directory as an unstaged change.
- s (split): If a hunk is too large, this splits it into even smaller pieces.
By choosing y only for the code related to your bug fix, you can commit that logic separately. The unfinished feature code remains in your working directory, safely tucked away until you are ready to finish it.
Why This Matters
By staging partial changes, you keep your commit history "atomic." Every commit becomes a clear, understandable unit of work. If you ever need to undo a specific change later, you won't be forced to roll back unrelated code that happened to be in the same file. This granularity is the secret to a professional and readable repository history.
Key Takeaway: Use git add -p to interactively stage specific hunks of code, allowing you to create clean, focused commits even when you’ve made multiple unrelated changes in a single file.