I am new to git and I am trying to experiment with it to understand the concepts particularly the branching and merging.
So here is my set up,
I have a master branch, I create a master text file with 'master' text.
Now I do git checkout -b branch
and create a branch.
I edit the branch 'parent' file and add one line of text.
Now If I commit this change and switch back to master, It won't affect as It shouldn't, as Branch changes should not reflect in the master branch.
However If I leave the branch uncommitted and switch to master, This change reflect there and git treats master file as edited, When I do
git status -s
It shows that master file with M.
Can anyone explain to me how the uncommitted changes are reflecting in the master branch?
You may switch branches with uncommitted changes in the work-tree if and only if said switching does not require clobbering those changes.
git commit takes a snapshot of all the tracked files in the index as a commit. A branch is a ref that points to a commit. In your case, the changes are still in the work tree. The branch doesn't know about them yet.
Working directly in master means that if you create bugs you have no other option for "going back" than to reverse/delete/reset commits, which is not a clean way of working and can cause you to lose the parts of the new code that were OK.
Git keeps your uncommitted changes when checking out another branch, which is very practical.
You can see this as uncommitted changes "belong" only to your working copy, and not to any branch or commit. They are independent. When you will commit the changes in a branch, they will of course change if the checkout has a different version for the file.
The only exception to this behaviour is if the branch change brings an uncommitted file to a different version, it which case the checkout is canceled:
A--B - feature
\
-C - master
Let's say commit B in the feature
branch changes a line to foo.txt
, and that you have the master
branch checked out. You have made a different change to foo.txt
.
You commit the change in master
and checkout feature
git add foo.txt
git commit -m "changed foo.txt"
git checkout feature
Here no problem, the change is recorded in master
and when you go to feature
foo.txt
is changed accordingly.
If you don't commit and try to checkout feature
, then Git will print an appropriate message, and keep the master
branch checked out:
git checkout feature
error: Your local changes to the following files would be overwritten by checkout:
foo.txt
Please, commit your changes or stash them before you can switch branches. Aborting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With