What is the need for Branching in Git? #


What are Branches?

  • Enable Parallel Work Without Interference: Branches let you work on multiple features or bug fixes independently, without affecting the main code base
  • Easy to Switch Branches: Use git switch to move between branches without losing work — Git handles the transition smoothly (git checkout is the OLD alternative)
  • Merge Branches to Combine Work: Once your feature is complete, you can merge it back into the main branch — keeping your work organized and your history clean
  • Delete Branches After Merging: After merging, you can safely delete the feature branch to keep your repo tidy — the commits are already part of the main history
  • Best Practice: Keep branches short-lived and focused — easier to manage, review, and merge
  • Branch Is Just a Pointer to a Commit: A branch simply points to the latest commit on that line of development — it's lightweight and fast - no performance impact
  • Automatically Moves with Every Commit: When you make a new commit, your current branch pointer moves forward to include it
Action Command Example
Create a Branch 🌱 git branch <branch-name> git branch feature-login
Switch to a Branch 🚀 git switch <branch-name> git switch feature-login
Create and Switch git switch -c <branch-name> git switch -c feature-login
List All Branches 📋 git branch git branch
Delete a Branch 🗑️ git branch -d <branch-name> git branch -d feature-login
Force Delete 💥 git branch -D <branch-name> git branch -D old-branch-that-is-not-merged

Give Examples of Different Types of Branches with a Practical Example #


Key Types of Branches

  • Integration Branch – Combine Work from Multiple Sources: An integration branch brings together code from different feature branches.
  • Feature Branch – Focus on One Task at a Time: A feature branch is used to work on a specific feature in isolation from the rest of the project
    • Create Feature Branches from Integration Branch: Start a feature branch from the latest version of the integration branch
    • Merge Feature Branches into Integration Branch: Once the feature is complete and tested, merge it back into the integration branch
  • Keeps the Codebase Stable and Clean: Integration branches act as control points — only reviewed and tested code is merged in
    • Best Practice: Keep integration branches stable — never commit unfinished code directly to them
  • Most Common Use Case: Use a dedicated feature branch for each user story, and merge it into integration branch when done.

Practical Example: Create a Feature Branch and Build a Feature

# You are connected to the main branch

# Step 1: Create a new feature branch
git switch -c feature-homepage

# Why? Feature branches help isolate work on 
# specific tasks or features. Keeps main clean.

# Step 2: Make a change in the feature branch
echo "<p>This is the homepage</p>" >> index.html

# Step 3: Stage and commit the change
git add index.html
git commit -m "Added homepage paragraph"

# Step 4: Switch back to main branch
git switch main

# Step 5: Merge feature branch into main
git merge feature-homepage

# Why? This integrates the feature into main.
# If no conflict, it's a fast-forward merge.

# Optional Step 6: Delete the feature branch
git branch -d feature-homepage

# Why? Feature is merged, so the branch is no
# longer needed. Keeps your branches clean.

# ===============================================
# Version-Specific Notes:
# ===============================================
# If you're using Git 2.23 or newer (recommended):
# - Use `git switch` to move between branches
# - Use `git switch -c` to create + switch

# Older versions of Git:
# - Use `git checkout` instead of `git switch`
# - Example: git checkout -b feature-homepage
# ===============================================


Fast-Forward Merge vs Merge Commit vs Merge Conflict #


  • Scenario: Imagine combining two branches in a Git project — sometimes it’s simple, sometimes complex
  • Fast-Forward Merge – The Cleanest Path: Happens when the main branch hasn’t moved ahead — Git simply moves the branch pointer forward. No extra commits. Simple and linear history.
  • Merge Commit – Needed When Branches Diverge: If both branches have progressed, Git creates a new commit that brings both sets of changes together. Helps preserve a clear history of parallel work.
    • Two Parent Branches: Merge Commit has Two Parent Branches
    • Merge Conflict – Manual Attention Required: If the same lines of a file are changed in both branches, Git cannot auto-merge. You must resolve the conflict manually and complete the merge.

Resolving A Merge Confict - A Step By Step Example

  • (Step 1) Create a Feature Branch from Main: Start by creating and switching to a new branch for your feature work

    git switch -c feature-update  
  • (Step 2) Modify the File in the Feature Branch: Open about.txt and change the content to: Welcome to in28minutes - Learn DevOps with us! Then stage and commit the update

    git add about.txt  
    git commit -m "Updated about.txt in feature branch"  
  • (Step 3) Another Developer Updates the Same File on Main: While you're working on feature-update, another team member edits the same line in about.txt on the main branch. They change it to: Welcome to in28minutes - Learn Spring Boot! They commit their change to main and push it.

  • (Step 4) You Switch Back to Main and Pull Latest Changes:

    git switch main  
    git pull origin main  

    Now your local main includes the other developer’s changes.

  • (Step 5) You Try to Merge Your Feature Branch:

    git merge feature-update  

    Git detects that both branches changed the same line in about.txt and throws a merge conflict.

  • (Step 6) Resolve the Merge Conflict Manually: Open about.txt. Git shows conflict markers like:

    <<<<<<< HEAD  
    Welcome to in28minutes - Learn Spring Boot!  
    =======  
    Welcome to in28minutes - Learn DevOps with us!  
    >>>>>>> feature-update  
    

    Resolve the conflict by combining both lines or choosing one. Example: Welcome to in28minutes - Learn Spring Boot and DevOps! Save the file.

  • (Step 7) Complete the Merge After Resolving:

    git add about.txt  
    git commit -m "Resolved merge conflict in about.txt"  
  • You Have Successfully Integrated Both Changes: This shows how real teamwork can cause merge conflicts — and how Git helps you safely resolve them.


Compare Gitflow vs GitHub Flow vs Trunk-Based Development #


What is Gitflow?

  • Scenario: Imagine multiple developers working on features, fixes, and releases at the same time — without a clear workflow, this could easily lead to confusion and broken code. Can we bring structure to this chaos?
  • Gitflow Workflow: A popular (and old) Git branching model that defines clear roles for each type of branch — making collaboration and delivery predictable and reliable
  • Defines Clear Roles for Every Branch:
    • main: always contains production-ready code
    • develop: integration branch for upcoming features
    • feature/*: separate branches for individual features
    • release/*: used to prepare for a new release
  • Enables Safe Parallel Development: Developers can work on their own feature branches without impacting each other or the main codebase
  • Simplifies Release Management: Use a dedicated release branch to finalize, test, and polish code before going to production
  • Supports Emergency Fixes Without Delay: Create a hotfix branch directly from main to fix issues quickly — then merge it into both main and develop
  • Keeps Production Stable While Development Continues: Features are only merged to main after thorough testing via develop and release branches
  • Ideal for Structured Teams and Long-Term Projects: Helps enforce discipline, consistency, and predictability in the software lifecycle
  • ⚠️ Word of Caution: Gitflow introduces a lot of complexity

What is GitHub Flow?

  • Scenario: Imagine you’re working in a fast-moving team building a modern web app. You want to ship features quickly, collaborate with others, and keep production stable. Can we use a simple workflow?
  • GitHub Flow – Simple, Modern, Effective: A lightweight Git workflow built around short-lived feature branches and pull requests
  • Start from Main – Always: Every new feature or bug fix starts from the main branch
  • Create a Feature Branch: Use git switch -c feature-name to isolate your work
  • Commit Often, Push Regularly: Keep your branch up to date and back up your work. Small commits help trace changes and simplify debugging.
  • Open a Pull Request Early: Share your work with teammates for feedback, discussion, and review. Collaboration starts even before you’re done!
  • Discuss, Review, Improve: Use GitHub comments, suggestions, and checks to ensure quality, catch bugs, and align with project goals
  • Merge to Main After Review: Once approved and tested, merge your branch to main.
  • Deploy Immediately: Merging to main means the feature is ready for production — deploy right away or let CI/CD take over
  • Lightweight: Lightweight and flexible compared to Gitflow

What is Trunk Based Development?

  • Scenario: Imagine a team releasing code multiple times a day. Long-lived branches would slow things down and increase merge pain. How do modern teams ship fast without chaos?
  • Trunk-Based Development – One Branch to Rule Them All: A development model where everyone works in a single main branch (called “trunk”) and commits frequently — keeping code always production-ready
  • One Shared Branch – The Trunk: Instead of maintaining multiple long-lived branches, all changes go to a single branch (typically main or master)
  • Small, Frequent Commits: Developers commit small chunks of work multiple times a day — helping catch issues early and reduce merge conflicts
  • Feature Toggles for Incomplete Work: Use toggles/feature flags (conditional statements within the codebase, enabling or disabling specific features) to hide incomplete features from users while keeping code merged
  • CI/CD is Mandatory: Every commit triggers tests and builds.
  • Short-Lived Branches Only: If branches are used at all, they live for a few hours or a day — not weeks. Most teams commit directly to trunk after validation.
  • Encourages Collective Code Ownership: Everyone works on the same codebase and takes responsibility for keeping it working
  • Fast Feedback Loops: Since commits are frequent and automated testing is instant, bugs are detected early and resolved quickly
Feature Gitflow GitHub Flow Trunk-Based Development
Release Frequency Less frequent, planned releases Frequent, even daily deployments Multiple deployments per day possible
Branching Model Uses multiple long-lived branches like main, develop, feature, release, and hotfix Uses short-lived feature branches off main Mostly works directly on main (trunk), or uses very short-lived branches
Main Focus Structure and process for managing features, releases, and fixes Speed and simplicity Fast feedback, rapid integration, always-ready-to-deploy code
Ideal For Large teams with multiple parallel efforts Teams focused on quick iteration and delivery High-performing DevOps teams aiming for continuous integration
Merge Conflicts Can be delayed due to long-lived branches Usually small due to short-lived branches Minimal conflicts due to continuous integration
My Recommendations Use for enterprise-level projects with formal release cycles Use for startups or small teams that deploy often Use for mature teams with strong CI/CD and automation testing skills

What is a Forking? #


  • Scenario: Imagine you're excited to contribute to an open-source project, but you don’t have permission to push changes directly to the main repository. How can you safely propose changes and collaborate?
  • Forking Creates Your Own Workspace: Forking makes a personal copy of the project on your GitHub account, giving you full control to experiment and build without affecting the original
  • No Need for Direct Access to the Original Repo: You don’t need write permissions — perfect for external contributors and community developers
  • Safe Place to Experiment and Learn: You can test, modify, and explore in your fork without worrying about breaking anything for others
  • Submit Changes via Pull Requests: After making improvements in your fork, you propose changes by opening a pull request to the original repository — changes are reviewed before being merged
  • Keeps the Original Project Protected: All changes are reviewed and approved before merging — ensures quality, security, and project integrity
  • Easy to Sync With Latest Updates: Even though you’re working in your fork, you can regularly fetch changes from the original repo to stay up to date
  • Empowers Open-Source Collaboration at Scale: Forking allows thousands of developers to work in parallel without stepping on each other

How does the Forking Workflow look like?

  • (Step 1) Fork the Repository on GitHub: Visit the original repository on GitHub and click the “Fork” button to create your own personal copy under your GitHub account Why? This gives you full access to make changes safely without affecting the original project
  • (Step 2) Clone Your Fork Locally:
    git clone https://github.com/your-username/project-name.git  
    Why? This brings your forked copy to your local machine so you can start working on it
  • (Step 3) Add the Original Repo as an Upstream Remote:
    git remote add upstream \
    https://github.com/original-owner/project-name.git  
    Why? This lets you fetch updates from the original project in case new changes are made there
  • (Step 4) Create a Branch for Your Work:
    git switch -c feature-improvement  
    Why? Working in a separate branch keeps your changes organized and makes collaboration easier
  • (Step 5) Make Changes and Commit: Edit files, add new features or fix bugs. Then stage and commit your changes
    git add .  
    git commit -m "Added feature improvement"  
    Why? Commits save your progress with context — what changed and why
  • (Step 6) Push Your Branch to Your Fork:
    git push origin feature-improvement  
    Why? This uploads your branch to your GitHub fork so others can view and review it
  • (Step 7) Open a Pull Request: Go to your fork on GitHub, switch to your branch, and click “Compare & pull requestWhy? This is how you propose your changes to the original project maintainers — they can review, discuss, and merge if approved

Forking vs Cloning #


  • Scenario: Imagine two different needs — one where you want to contribute to a project you don’t own, and another where you simply want to use or explore the code. Should you fork or just clone?
  • Forking Gives You a Personal Copy on GitHub: Forking creates a separate repository under your GitHub account. You own it. You can push changes, create branches, and open pull requests to the original project.
    • Cloning Brings Code to Your Local Machine: Cloning simply copies the repository to your local system. You can explore, edit, and test code — but you don’t get a hosted copy on GitHub unless you manually create one.
  • Fork When You Want to Contribute Publicly: If you want to contribute to an open-source project without having write access, fork it first, then clone your fork.
    • Clone When You Just Want to Use or Learn: If you're just studying the code or using it as a dependency in your own project, cloning is enough.
  • Forks Are Tracked on GitHub: GitHub knows a fork’s relationship with the original repository, which helps in tracking contributions and simplifying pull requests.
    • Clones Are Not Connected by Default: A clone has no GitHub-level relationship with the original project. You’d have to manually add remotes if you want to contribute
  • Forking Enables Pull Requests Easily: After committing changes to your fork, you can propose them using GitHub’s Pull Request feature.
    • Cloning Requires Manual Setup for Contributions: If you clone directly from the original repo, you cannot push unless you have permissions — contributing requires more setup.
Action Use Forking When... Use Cloning When...
Learning You don't need to fork You can just clone
Contributing to a Project You want to contribute to a project you don’t own You already have push access
Remote Management You need a cloud-hosted editable copy You just need a local copy

What is Detached HEAD in Git? #


  • Detached HEAD – Not Pointing to a Branch: When you run git checkout <commit-id>, Git moves HEAD to a specific commit instead of a branch — you're now in a detached state
  • You Are Not on a Branch Anymore: In this mode, HEAD is not following any branch, so new commits won't belong to a named branch unless you explicitly create one
  • Risk of Losing Work – Commits May Be Abandoned: If you make commits in detached HEAD mode and switch away without saving them, those commits can be lost
  • Safe Usage – Read-Only or Temporary Exploration: This mode is useful when you want to explore an older commit, test a bug, or browse history without making changes
  • Want to Keep Your Work? Create a Branch: If you do commit something and want to keep it, run git switch -c <branch-name> to save your changes to a new branch
  • Why This Matters: Understanding detached HEAD helps avoid accidentally losing work or making changes you can’t trace
  • Most Common Use Case: Inspecting an older state of the project without affecting any active branches
  • Pro Tip: Always create a branch before committing if you plan to keep the changes
  • Important to Remember: Detached HEAD is not dangerous, but it requires care — you're off the main road, so mark your trail if you plan to return to it later!