Branches
A branch points to a commit. The currently selected branch, if any, is the one that HEAD points to.
When we add a commit, the selected branch, and only this branch, is updated to point to the new commit.
As such, branches evolve independently.
We usually merge branches back to main. If main has evolved in a conflicting since then, we decide as to how to solve the conflict, that is, which version of the file prevails.
list branches
git branch # local branches
git branch -a # include remote branches
create, rename, delete branch
creating a branch does not switch to it.
git branch dev
git branch -m master main
git branch -d dev
Branch switching and stashing
switching to a branch means to have HEAD pointing to the branch, which points to a commit. The idea of switching to a commit is to get a clean working directory and index that match this commit, so we may start working from this snapshot.
This also means that any unsaved work in the working directory or in the index before switching may be lost. As such, we either commit all changes, or use the stash
technique to locally save the state of the working directory and the staging area.
There is one exception: if we create a branch from the current one and switch into it, our working directory and staging area are not changed. Instead we keep our dirty working directory and staging area. This is because git realizes that both branches point to the same commit for now, and as such, the changes we made still make sense because they change this share commit, and we may use those changes to make the first commit on the distinct branch.
switch to branch
git switch dev
git checkout dev
stash and pop
save the working directory and staging area with stash:
git stash
git switch dev
restore the working directory and staging area, assuming we are back on the correct branch. the --index flag restores the staging area as well.
git stash pop --index
switching to a branch that comes from a remote
if the remote branch such as origin/dev does not have a matching local branch, the git switch command may create the dev local branch and switch into it.
git switch dev