Sachin Patil

Sachin

Free software developer & Emacser

Commit part of a file

We seldom have a situation where only a part of a file needs to be committed. This may be due to the fact that within a file, we do not want to commit those changes of which we are unsure about. Let me introduce you to --patch, one of the options of git-add.

I have few parts in a file, lets call them “hunk”. Some of the hunks, I wish to commit, others I don’t want to commit(I’m not sure if they are worth it).

As usual, I start by adding a file, but this time, instead of using git add <FILENAME>, I’ll include an option --patch to git-add,

git add --patch <FILENAME>

This will give me a chance to review my changes. Git carefully scans my changes, and will prompt me for every hunk he detects modified content. I’ll have an option to stage(y), do not stage(n), quit(q), stage all hunks(a), and so no. Full list of options with explanation is displayed while using option --interactive with git-add.

I want to stage the first hunk, I will say ’y’ here as show in below snapshot.

Commit ReadMe.org warning
Figure 1: Commit ReadMe.org warning

Git will go head and present me with second hunk. I’m not sure of these changes and I’ll say ’n’ at the prompt.

Do not commit use-package test
Figure 2: Do not commit use-package test

Git will not stage that piece of change, and will jump to next hunk. I want to commit this hunk. I’ll enter ’y’ as show below.

Commit prog-mode-hook
Figure 3: Commit prog-mode-hook

If I check the status of the file after completed answering the prompts, I still see that file in un-staged area. This is similar to modifying the file after staging. This is expected as I have partially staged the file(Note that st is an alias for status).

Git status
Figure 4: Git status

Further, git diff will display the changes, I ignored during the interactive mode.

Git diff
Figure 5: Git diff

But git diff --cached will have all staged hunks.

Git diff cached
Figure 6: Git diff cached

Ensuring that I have what I needed in my staging area, I can go ahead and commit my changes.