Creating Branches in Git

We’ve been mak­ing great progress on our project so far. How­ev­er, change things up a bit and make some code changes in the project. 

Our changes might break the project, so we need to do it in a way that is iso­lat­ed. We will use a new branch in Git to make the changes and then merge that branch back in when we’re done.

To cre­ate a new branch, we want to first make sure we can a clean work­ing directory.

  $ git status
  On branch master
  nothing to commit, working directory clean

Now let’s cre­ate a new branch called ri_refactoring-code. I’m namep­sac­ing the branch with my ini­tials and then giv­ing a descrip­tive name of what I’m doing in the branch. You can name branch­es what­ev­er you want, and the name­spacing isn’t required. I sim­ply find it helpful .

To cre­ate branch­es we use the git-branch com­mand, fol­lowed by the branch name.

$ git branch ri_refactoring-code

To see a list­ing of branch­es we run git-branch with­out any arguments.

$ git branch
  * master

We see our new­ly cre­at­ed branch. 

Right now the new branch is exact­ly like the master branch. The new branch is based off master because that was the branch we had checked out at the time of run­ning git-branch.

The aster­isk next to the master branch in the out­put above denotes that is the cur­rent branch. 

To switch over to our new branch we use git-checkout, pass­ing in the name of the branch we want to check out.

$ git checkout ri_refactoring-code
  Switched to branch 'ri_refactoring-code'

Alright, now we’re ready to change the code! Don’t for­get: any­thing we change in the cur­rent branch will not impact the master branch.

Let’s make a change in the 1-basics.rb file and add a new puts state­ment at the top, below the orig­i­nal one. This is only a small change but we want to get to the next task: merg­ing the changes in our ri_refactoring-code branch into our master branch.

Before we can do that we have to first have to add and com­mit the changes.

$ git commit -a -m "adding puts statement at the top of the basics file"

With that done, we can do our merge, which we cov­er in the next chapter.