ZANARDI Bruno

Software Developper

About
Resume

Git Blog

How To: Manage changes

previous next

related commands:
add reset

This post explain how to add / remove some changes from index before a commit.

Partially add changes

You opened a file for a fix, but you did other (needed) changes unconnected with the reason why you firstly opened the file: an atomic commit is impossible.
Do not put all your changes in a commit with a message like “lots of changes”… use add -p! The -p option, aka --patch, allows you to chose which hunks of changes you will add to the stage for the commit.

$ git status
On branch master Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: <file> $ git add -p <file>
$ git status
On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: <file> Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: <file> $ git commit -m "first changes"
$
$ git add -p <file>
$ git status
On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: <file> $ git commit -m "second changes"
$
$ git status
On branch master nothing to commit (working directory clean)

As you noticed, after a add -p, the file is in the Changes to be commited section and the Changed but not updated section. Obviously. A part of changes is staged, the other part isn’t.

Warning:
Never use commit -a after a add -p or you will lose all your “ninja” work with hunks.

With the -p option, git add will cut changes in hunks and will ask you if you want to add this hunk to stage or not. Hunks are made using unchanged lines, so if two changes are too close they will be put in one hunk. But Git will offer you a lot of functions during the process and you will be able to split or edit hunks.

Partially remove changes

You staged a file with git add but you want to remove a change from the stage? reset offers you the solution with the -p option!

$ git reset -p HEAD <file>

This is exactly the opposite of git add -p, you will be able to chose which hunks you want to remove.

previous top next

Reminder

add

Add file content / changes in file content to index or remove file from tracking list if file doesn’t exist anymore in working directory

$ git add -A <file>

Add parts of changes in file content to index. Parts are selected interactively within hunks of changes generated by git

$ git add -p <file>

reset

Remove parts of changes in file content from index. Parts are selected interactively within hunks of changes generated by git

$ git reset -p HEAD <file>

Come back to previous commit

$ git reset --soft HEAD^
previous top next