4. Branches

Branches are a fundamental concept in version control. They act as independent lines of development within your project, allowing you to experiment with changes, fix bugs, or develop new features without affecting the main codebase.

Think of branches like different forks in a road. The main road represents the main branch (often named main or master) of your project, which holds the stable, publicly-available version. Branching allows you to create new roads (branches) to explore different directions without altering the main road.

Key Functions:

  • Creating branches: You use the git branch <branch_name> command to create a new branch. This essentially creates a pointer to a specific commit in your project’s history, which becomes the starting point for your branch’s development.
  • Switching branches: You can switch between branches using the git checkout <branch_name> command. This tells Git to focus on the specified branch and its history.
  • Committing changes: When you make changes and commit them, you’re creating a new snapshot of your project’s state specific to the branch you’re currently working on.
  • Merging branches: Once you’re satisfied with the changes in a branch, you can merge them back into the main branch using git merge <branch_name>. This integrates the commits from your branch into the main branch’s history.
  • Deleting branches: When a branch is no longer needed, you can delete it using git branch -d <branch_name>. However, it’s important to ensure the branch has been merged into the main branch or another relevant branch before deletion.

Benefits of using Git branches:

  • Isolation: Branches allow you to experiment and isolate changes without impacting the main codebase. This prevents accidental corruption of the stable version.
  • Collaboration: Team members can work on different features or bug fixes simultaneously on separate branches. This promotes efficient development and faster project completion.
  • Feature development: Branches enable you to develop new features without affecting the main codebase until the feature is ready for integration.
  • Bug fixing: You can create a dedicated branch to fix a bug without affecting ongoing development in the main branch.

Example…

$ git switch -c b2
Switched to a new branch 'b2'
$ touch file.txt
$ git add file.txt
$ git commit -m "comment"
$ git push -u origin b2
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 311 bytes | 155.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
remote:
remote: To create a merge request for b2, visit:
remote:   https://gitserver/jonas/demo/-/merge_requests/new?merge_request%5Bsource_branch%5D=b2
remote:
To https://gitserver/jonas/demo.git
 * [new branch]      b2 -> b2
Branch 'b2' set up to track remote branch 'b2' from 'origin'.