Create and Manage Git Branches

I am not an expert at this but here are my notes on creating and managing Git Branches. Why do we create branches? Well the main reason we use version control is so that we can always go back to a point in time in our sources where we know what the state of the code is. Having branches make that easy. The master branch contains the latest and greatest "working" version of the code. Everytime we make a change, we create a new branch, make our changes, test, and then when finally ready , we merge it back to our master branch. At this time when we are ready to push say to production, we create a "tag" or another branch.

Notes on git branch commands

Create the branch on your local machine and switch in this branch :

$ git checkout -b [name_of_your_new_branch]

Push the branch on github :

$ git push origin [name_of_your_new_branch]

When you want to commit something in your branch, be sure to be in your branch.

You can see all branches created by using :

$ git branch

Which will show :

* approval_messages
  master
  master_clean

Add a new remote for your branch :

$ git remote add [name_of_your_remote]

Push changes from your commit into your branch :

$ git push origin [name_of_your_remote]

Update your branch when the original branch from official repository has been updated :

$ git fetch [name_of_your_remote]

Then you need to apply to merge changes, if your branch is derivated from develop you need to do :

$ git merge [name_of_your_remote]/develop

Delete a branch on your local filesystem :

$ git branch -d [name_of_your_new_branch]

To force the deletion of local branch on your filesystem :

$ git branch -D [name_of_your_new_branch]

Delete the branch on github :

$ git push origin :[name_of_your_new_branch]

The only difference is the : to say delete, you can do it too by using github interface to remove branch : https://help.github.com/articles/deleting-unused-branches.

Hard Reset: Loose all Local Changes and Get the Remote

git fetch --all
git reset --hard origin/master

OR If you are on some other branch

git fetch --all
git reset --hard origin/your_branch

Explanation:

git fetch downloads the latest from remote without trying to merge or rebase anything.

Then the git reset resets the master branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/master

[*]: It's worth noting that it is possible to maintain current local commits by creating a branch from master before resetting:

git checkout master
git branch new-branch-to-save-current-commits
git fetch --all
git reset --hard origin/master
After this, all of the old commits will be kept in new-branch-to-save-current-commits. Uncommitted changes however (even staged), will be lost. Make sure to stash and commit anything you need.