How to commit only part of a file’s changes in Git ?

To commit only part of a file’s changes in Git, use interactive staging (git add -p or git add --patch). This allows you to review and select specific changes (hunks) to include in your commit. Here’s how:

Step-by-Step Guide

  1. Start interactive staging:
   git add -p <file>  # Replace `<file>` with the path to your file
  • This opens an interactive prompt showing chunks of changes in the file.
  1. Review and select changes:
    Git will display a “hunk” (a block of changes) and prompt you with:
   Stage this hunk [y,n,q,a,d,s,e,?]?
  • Common options:
    • y (yes): Stage the hunk.
    • n (no): Skip the hunk.
    • s (split): Split the hunk into smaller parts (if possible).
    • e (edit): Manually edit the hunk (advanced).
    • q (quit): Exit the interactive session.
    • ?: Show help for all options.
  1. Split large hunks (if needed):
  • If a hunk contains changes you want to split, press s to divide it into smaller hunks for finer control.
  1. Repeat until done:
    Continue selecting y or n for each hunk until all desired changes are staged.
  2. Commit the staged changes:
   git commit -m "Commit message for selected changes"
  1. Commit remaining changes (optional):
  • Repeat the process for other parts of the file or commit the rest later.

Example Workflow

# 1. Start interactive staging for a file
git add -p src/app.js

# 2. Git shows a hunk:
- console.log('Debug message');
+ const result = calculate();
Stage this hunk [y,n,q,a,d,e,?]? y  # Stage this change
# 3. Commit the staged changes
git commit -m "Add calculation logic"

# 4. Remaining changes (if any) stay uncommitted

Alternative: Stage Specific Lines with git add -e

For precise line-by-line control:

  1. Open the file in your editor and manually delete the lines you don’t want to stage.
  2. Save the file and stage it:
   git add <file>
  1. Undo the edits (restore the original file):
   git checkout -- <file>
  1. Commit the staged lines.

Key Notes

  • Unstaged changes remain: Only the selected hunks are staged; the rest stay in your working directory.
  • Verify staged changes: Use git diff --staged to check what’s been staged before committing.
  • Undo mistakes: Use git restore --staged <file> to unstage all changes in a file and start over.

Best Practices

  • Test your code after partial commits to ensure the unstaged changes don’t break functionality.
  • Use git checkout -p <file> to discard specific changes instead of staging them.

Leave a Reply

Your email address will not be published. Required fields are marked *