Working with branches

Now that we know how to create commits and manage files, let's practice doing that on other branches, and merging back to main later. First, notice how git status has already been telling you at every step what branch you're on. We can also use git branchto list all the available branches and which one we're on.

$ git status
# On branch main
# nothing to commit, working tree clean
$ git status -sb
# ## main
$ git branch 
# * main
$ git branch -av
# * main c5ac38c Added a comment

Creating a new branch

Say we want to add a README.mdfile to our project. This file is shown to users when they look at your repository, so we'll want to take some time to get it right. Let's start by making a feature branch

$ git switch -c add-readme
$ git branch -av
# * add-readme c5ac38c Added a comment
#   main       c5ac38c Added a comment

Notice how even though we're on a new branch, both branches are actually at the same commit. Let's use another command to see the full history of the repository:

That's a long command, but worth saving or making an alias for, as it will show a lot more information in a much more concise way than the default git log will. We can see that main and add-readme both point to the same commit and HEADpoints to add-readme. This makes sense: we've branched off but haven't done anything new yet. Let's do that.

Now we can clearly see that mainends at Added a commentwhile add-readmegoes a bit further.

Because add-readmehad everything maindoes, we only had to fast-forward to catch up to add-readme. This is the cleanest type of merge, but is still important to demonstrate.

Merge conflicts

We've already pointed out how merge conflicts can arise when two branches attempt to modify the same files. Let's take a look:

So far, we've made a new feature branch and added a commit that modifies our file, but we haven't merged this branch yet. Now, let's branch off of mainyet again and do the same thing:

The setup is done:

Two branches, two commits, one file.

Git can't figure out what to do about hello.py. Let's see what it did:

Git sectioned off the difference changes, one section for HEAD(meaning, the current state of the main` branch) and the other for the incoming changes of branch2. As discussed in Merge Conflicts, the right thing to do is to analyze the situation with context. Let's assume for our example case that we really do want both print statements. The correct resolution is then:

Let's save and commit that

Chances are, your IDE will offer to help out here. For example, VS Code will open conflicting files in its Merge Editor, while Sublime Text offers a standalone application called Sublime Merge. Apps like these tend to have a three-paned layout: the current branch, the incoming changes, and the new resulting file.

Last updated

Was this helpful?