Why would I want stage before committing in Git?
One practical purpose of staging is logical separation of file commits.
As staging allows you to continue making edits to the files/working directory, and make commits in parts when you think things are ready, you can use separate stages for logically unrelated edits.
Suppose you have 4 files fileA.html
, fileB.html
, fileC.html
and fileD.html
. You make changes to all 4 files and are ready to commit but changes in fileA.html
and fileB.html
are logically related (for example, same new feature implementation in both files) while changes in fileC.html
and fileD.html
are separate and logically unrelated to previous to files. You can first stage files fileA.html
and fileB.html
and commit those.
git add fileA.html
git add fileB.html
git commit -m "Implemented new feature XYZ"
Then in next step you stage and commit changes to remaining two files.
git add fileC.html
git add fileD.html
git commit -m "Implemented another feature EFG"
When you commit it's only going to commit the changes in the index (the "staged" files). There are many uses for this, but the most obvious is to break up your working changes into smaller, self-contained pieces. Perhaps you fixed a bug while you were implementing a feature. You can git add
just that file (or git add -p
to add just part of a file!) and then commit that bugfix before committing everything else. If you are using git commit -a
then you are just forcing an add
of everything right before the commit. Don't use -a
if you want to take advantage of staging files.
You can also treat the staged files as an intermediate working copy with the --cached
to many commands. For example, git diff --cached
will show you how the stage differs from HEAD
so you can see what you're about to commit without mixing in your other working changes.
- Staging area gives the control to make commit smaller. Just make one logical change in the code, add the changed files to the staging area and finally if the changes are bad then checkout to the previous commit or otherwise commit the changes.It gives the flexibility to split the task into smaller tasks and commit smaller changes. With staging area it is easier to focus in small tasks.
- It also gives you the offer to take break and forgetting about how much work you have done before taking break. Suppose you need to change three files to make one logical change and you have changed the first file and need a long break until you start making the other changes. At this moment you cannot commit and you want to track which files you are done with so that after coming back you do not need to try to remember how much work have been done. So add the file to the staging area and it will save your work. When you come back just do
git diff --staged
and check which files you changed and where and start making other changes.