In the first post of this beginner's guide to Git and GitHub, you learned how to create a repository. Today, I will introduce you to Git branches. Git branches are independent lines of development within a repository, allowing for parallel work and feature separation. This beginner's guide will walk you through a Git branch example.
Avatar
Latest posts by Edem Afenyo (see all)

The first article in this Git series was a beginner-friendly introduction to Git and GitHub, with a focus on how to get started installing Git, creating repositories, and connecting them to GitHub for online collaboration. This article takes things a little further with a scenario-based dive into Git branches. Branches are an essential concept when working with Git and GitHub. What is a branch and what is it used for? Let’s find out.

Prerequisites

In this tutorial you are going to learn about branches through an introduction to making contributions to an open-source project. The dummy project uses Python to display system information. You can find the open-source repository on GitHub. Open it in a web browser, and let’s get started.

You will need a GitHub account, as shown in the previous article.

I used Git 2.34.1 on Ubuntu 22.04 for WSL in this tutorial, but you can use any version of Linux on which you can install Git.

Branches in Git

It is often helpful for beginners to see a branch as an individual line of development. Branches allow you to easily head off in a different direction of development while giving you the freedom to return to your old state with minimum fuss. You can work simultaneously with other collaborators on separate branches without introducing errors into your production source code.

For example, if you were working on an Ansible playbook, you would have made a series of commits to keep track of your work. A commit in Git is a snapshot of your codebase at a specific point in time, capturing changes along with a descriptive message. A series of commits can be called a branch.

If you wanted to test a new addition to the project, you would use a new branch for the new changes without compromising the master branch. The master branch, traditionally the default branch in Git repositories, represents the primary, often production-ready, line of development. You can switch between the new branch and the master branch while you develop your product. A branch helps you isolate and switch between independent lines of work.

Technically, a branch is a named pointer to the latest commit in a sequence of commits. This definition is what sets Git branches apart from other version control systems and gives Git much of its allure. For example, Subversion implements branches as whole copies of the files in the master branch, which you can edit separately. This makes Subversion branches more heavyweight than Git branches as they are slower to create and manipulate, especially as your codebase grows.

Although the definition may seem difficult to comprehend, the tutorial will simplify the concepts.

Fork vs. Clone

Forking and cloning are both ways of getting your own copy of a GitHub repository without manually calling Git Init, which initializes a new Git repository and begins tracking an existing directory. The main difference between the two is that forking creates a duplicate repository (a fork) under your account on GitHub, while cloning creates a duplicate outside GitHub, usually on your local computer.

Since you are not likely to have push access to a public repo (short for repository) if you are not its owner, cloning can be a workaround. However, cloning a public repo can present problems later when you want to push upstream (upload local changes to the repository). The solution to this problem is to first fork the public repo to obtain a fully owned replica on GitHub, and then clone your fork to your local machine.

For this tutorial, you need a copy of the open-source repo you can edit. Open the public repo and, after logging in to GitHub, select Fork to create your fork.

Forking a repository

Forking a repository

Give the repository a name under your account. Uncheck Copy the main branch only to copy all branches of the repo. Finally, click Create fork to get your own copy.

Creating a fork

Creating a fork

Generate a Personal Access Token and choose All repositories under Repository access. Under Repository permissions, set Administration and Contents permissions to Read and write to enable you to interact with the repo via the command line.

Scoping personal access token permissions

Scoping personal access token permissions

Click Generate token and then copy the token, as it will be used as your password when interacting with the repo from the command line.

Generating a personal access token

Generating a personal access token

Next, navigate back to your GitHub home, click on the new forked repo, and then click Code as in the shot below to reveal the URL for your repo. Copy the URL for the next step.

Copying the URL of a repository

Copying the URL of a repository

Open a terminal on your local machine, and use the git clone command as follows to clone the repo. (If you haven't installed Git yet, refer to the first post of this Git tutorial.)

git clone <url-of-repo>

If all goes well, you will receive notice that everything has been cloned to your local machine.

Cloning a repository

Cloning a repository

Configuring the local repo

Switch into the local repo as follows:

cd branches

First, to identify the author of commits, set up the email and username details for this repo as is explained in more detail in my introductory article.

git config user.name "YourUserName"
git config user.email "YourName@YourMail.com"

Second, cache your credentials for the remote repo so you do not have to enter them repeatedly during this tutorial. Configure the inbuilt credential helper to store your credentials for a day, i.e., 86,400 seconds. This value is entirely at your discretion but should be in seconds.

git config credential.helper "cache --timeout 86400" 

Run git push twice to ensure the credentials have been cached. On the first run, you will be asked to key in your credentials. The password is the personal access token you generated earlier on.

Keying in credentials for a repository

Keying in credentials for a repository

On the second attempt, the command should run without your input.

git push
Running git push with cached credentials

Running git push with cached credentials

Listing branches

At this point, you can begin your practical introduction to branching by listing all the branches that are available on your local repo with git branch, which is short for git branch --list.

git branch 
image9

image9

Listing branches

As it stands, your repo has only the main branch. The main branch in Git is the default primary branch where development occurs and is typically the source of truth for the production code. This is usually sufficient to begin making contributions as a collaborator; however, there may be other branches on the remote end. You can list them with the -r switch.

git branch -r
Listing remote branches

Listing remote branches

From the results you can see that there are two remote branches listed, in the format <repository/branch>.

In the previous article, we created a remote (short for remote repository) that we named origin and manually mapped it to a new URL of a GitHub repository. We could have called it by any other name, but origin is a common choice among Git users.

origin/HEAD -> origin/main means that origin/HEAD is pointing to origin/main. This signifies that the branch named main is the branch currently in use (HEAD) in the remote repository named origin. Thus, when someone clones the repository without specifying a branch, they will default to the main branch, which means any changes they make (like commits) will be applied to the branch named main unless they switch to a different branch.

In this article, we did not have to create origin. Git automatically creates a remote—a reference in your local cloned repository that points back to the repository's URL. This remote is usually named "origin." The purpose of this is to make it easy for you to fetch updates from or push changes back to the original repository without having to remember or re-enter its URL every time. If a name is not specified, this remote is named origin.

The local main branch is also automatically set up to push and pull from the main branch of the cloned remote repository.

You can view the details of your remote origin with this command:

git remote show origin
Viewing the configuration of a remote

Viewing the configuration of a remote

Note that the Fetch URL and the Push URL will point to your fork of the repo.

Apart from configuring the remote of your local clone, git clone also modifies your working directory to reflect the state of the latest commit (version of the files and directories in a repository) on the newly created branch. This modification is known in Git parlance as a checkout.

So, if you list the files in your current working directory with the ls command, you should have the same files as the GitHub repo you cloned.

Listing the contents of the present working directory

Listing the contents of the present working directory

Use the cat command to view its contents.

cat check-system.py
Viewing the contents of check system.py_

Viewing the contents of check system.py_

import platform
import os

print(f"System: {platform.system()}")
print(f"Hostname: {os.uname()[1]}")

Run it with Python 3 as below to confirm that the script works.

python3 check-system.py
Testing check system.py_

Testing check system.py_

The script will display the operating system and hostname on your computer.

After having a feel for the state of the project, you may want to contribute some improvements. With the power of branching, you can safely make all changes to the working directory without affecting the state of the main branch. When you are satisfied, you can safely merge the changes.

Creating a branch

Let's create a new branch named convert-os-to-platform:

git branch convert-os-to-platform

Next, we use the git checkout command to leave our current branch and switch to the new branch that we created with the previous command.

git checkout convert-os-to-platform
Creating and switching to a branch

Creating and switching to a branch

You can use the git branch command one more time to verify the current branch you are on.

git branch

 

Listing local branches

Listing local branches

The asterisk indicates the active branch.

Now that we are on a new branch, we can make changes and commit them. Edit check-system.py and replace its contents with the code below.

import platform

print("Retrieving System information…\n")
print(f"System: {platform.system()}")
print(f"Hostname: {platform.node()}")

Save the file with the same name, and run the script with Python 3 one more time to confirm that the improvements did not break the program.

python3 check-system.py
Testing check system.py after modification

Testing check system.py after modification

Next, we stage our changes, which means putting files in a temporary directory to be reviewed and committed later:

git add .

With git status, we can see which files have been staged.

git status
Checking the active branch with staged changes

Checking the active branch with staged changes

The following command commits the staged files to the repo and adds a comment to the commit.

git commit -m "use platform for hostname check instead of os"
Committing changes to a branch

Committing changes to a branch

Let’s check the status of potential changes to our branch again:

git status
Checking the status of available changes after committing

Checking the status of available changes after committing

Note that so far, we only committed the changes locally, that is, we didn't upload the changes to GitHub.

Pushing a branch to GitHub

As it stands, we cloned the branch named main from GitHub and made a local branch off it. convert-os-to-platform exists only in the local repo. You can push it to GitHub to have it in the remote repo while updating origin with tracking information (-u).

git push -u origin convert-os-to-platform

You should receive feedback indicating that the push was successful and tracking information between the remote and local branches has been set up.

Pushing a local branch upstream

Pushing a local branch upstream

Open the repository on GitHub in your web browser to confirm that a new branch has been created and populated. The number of branches should increase to two, and there should be an extra entry in the list of branches.

Listing branches on GitHub

Listing branches on GitHub

Conclusion

In this guide you learned the basics of how to work with branches in Git and GitHub. In my next article, I will explain how to merge branches and to contribute to a public project.

Articles in seriesA Git/GitHub beginner's guide
0 Comments

Leave a reply

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2023

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account