Understanding git branching and staging files
I'm a bit confused about the benefits of branching in git.
If I create a branch, say, b1 and switch to this branch, any changes I make are visible if I switch back to the master branch.
Performing a git status in the master branch shows changes from the b1 branch.
I understand that changes need to be commited in b1 first, but how is one meant to manage multiple branches without accidentally commiting a change from another branch开发者_运维问答?
If you notice right after you've switched to master that you forgot to stage or commit some changes, you can just switch back immediately with git checkout b1
, of course, and then commit them.
However, you're right that it's very easy to commit changes on the wrong branch. Fortunately, git's branches are very lightweight - they're just a pointer to the tip of the branch in the commit graph - and git has good tools for rewriting the history so that it looks as you would like. Exactly what you'd need to do depends on the sequence of what you'd done, but there are lots of questions on Stack Overflow that deal with this. (Or you can just ask a new one if it's not clear.) Here's simple example:
- How to fix committing to the wrong Git branch?
... or if you'd done lots of commits on master that you suddenly realize are too controversial, and should be on a new topic branch you can do the following:
# Check that git status is clean and you really are on the master branch:
git status
# Create a branch based on your current position:
git branch controversial
# Move master back to the last non-controversial commit, making
# sure that the working tree and index match:
git reset --hard <NON-CONTROVERSIAL-COMMIT>
If there were already lots of commits on your existing branch b1
, then you could cherry-pick those from master:
# Switch back to `b1`:
git checkout b1
# Cherry-pick the commits that you'd rather were on b1:
git cherry-pick <CONTROVERSIAL-COMMIT-A>
git cherry-pick <CONTROVERSIAL-COMMIT-B>
# Switch back to `master`:
git checkout master
# Reset master back to the last non-controversial commit, making
# sure that the working tree and index match:
git reset --hard <NON-CONTROVERSIAL-COMMIT>
... of if you have lots of commits on master that should be on b1 you can use git rebase
.
In short, it's easy to recover from this kind of thing - you just have to understand what the commit graph looks like where you are, and what you'd rather it looked like.
If you are using git from the command line, a nice thing is to write the current branch to the bash prompt, e.g.
http://railstips.org/blog/archives/2009/02/02/bedazzle-your-bash-prompt-with-git-info/
This way you dont have to type "git branch" all the time to know what branch you are commiting to right now.
精彩评论