Git: Partial commits
The staging area
When using git commit -a from the previous chapter, git commits all changes at once.
To be more careful with committing files, git allows changes to be "staged" before saving them as a commit. That's what the git add actually does; it adds a file to the staging area.
This way, only the relevant changes will end up in the commit.
It is also possible to stage only parts of a file, to leave leave unrelated changes out of the commit.
Using the staging area
First find out what changes you have:
- Finding local changes:
# see a status report; which files have been changedgit diff
# see the exact difference, which lines have been changed
Then add the files you want:
- Little tips
If this particular usage of git add is a bit confusing, you can also use git stage instead.
It's just a synonym, and might work a bit better conceptually.
Also don't forget about the nifty tab-completion bash offers.
- Adding files to the staging area:
git add filename1 filename2 etc..
Now, git status shows which files are added, and which are left out. You can even type the git add command again, to add more files.
Watching staged changes
Things get interesting: git diff will only show the remaining, unstaged, changes! It becomes easy to see which changes you need to add.
The staged changes can be requested separately:
- Historical note
In previous versions of Git, the staging area is referred to as "the index" or "the cache".
You'll still find git diff --cached in other tutorials.
- Seeing staged changes:
git diff --staged
When the staging area looks exactly as you'd want, you can commit it:
- Committing the staging area:
The git status command shows you how to unstage changes. To make the staging easier, I highly recommend these aliases:
- Unstaging changes:
git config --global alias.unstage "reset HEAD" git config --global alias.staged "diff --staged"
Now you can do things like:
- Staging example:
git stage file1 file2
# `git stage` is the same as `git add`git staged
# see what you stagedgit unstage file1
# unstage the wrong file
# and when you're done:git commit
The only exception is the initial import. Those files can be unstaged using:
- Unstaging new imported files:
git rm --cached filename
# remove a NEW file, from the cache only
Staging parts of a file only
By staging only parts of a file, only those changes will be committed.
- Stage parts of a file:
git add --patch filename
For each change, you will be asked what to do with it. Type the letter, and press enter.
|y||yes; stage this change|
|n||no; don't stage this change|
|s||split; cut the change in smaller parts|
|e||edit; manually define the part to split|
|?||help for the remaining options|
Afterwards, with git status you'll see the file is partially staged. and the remaining changes are left in the working tree.
The staged changes will be included in the commit, the remaining changes will be left out.
After getting the staging area, it's time for branches.