Git Branches

1 min

Table of contents

  1. Why Branches?
  2. Branches in Action
  3. Merge vs Rebase
  4. Essential Commands
  5. Recommended Workflow

1. Why Branches?

Problem without branches:

  • Everyone codes on main
  • Total chaos, permanent conflicts
  • Broken code all the time

Solution: Branches!

  • main = always stable
  • feature-login = you develop the login
  • feature-api = a colleague develops the API
  • hotfix-bug = urgent fix

Each in their own corner, merge when it is ready!

Back to table of contents

2. Branches in Action

bash
mkdir demo-branches && cd demo-branches
git init

# Starting base
echo "print('App v1.0')" > app.py
git add . && git commit -m "Initial version"

# Create and switch to a new branch
git checkout -b feature-login
echo "print('Login system')" > login.py
git add . && git commit -m "Add login"

# Go back to main
git checkout main
echo "print('App v1.1')" > app.py
git add . && git commit -m "Update main"

# See all branches
git branch --all

# Merge the feature
git merge feature-login

Result: Both developments are combined!

Back to table of contents

3. Merge vs Rebase

MERGE:

bash
git merge feature-branch    # Creates a merge commit
  • History: shows that 2 branches were combined
  • Safe and simple

REBASE:

bash
git rebase main             # "Moves" your commits after main
  • History: linear, clean
  • More complex

Recommendation: Start with MERGE!

Back to table of contents

4. Essential Commands

CommandAction
git branchList the branches
git checkout -b <name>Create + switch to a branch
git checkout <name>Switch branch
git merge <branch>Merge a branch
git branch -d <name>Delete a branch
git push origin <name>Push a branch

Back to table of contents

Simple and effective workflow:

  1. New feature:

    bash
    git checkout main
    git pull
    git checkout -b feature-nouvelle-fonctionnalite
  2. Develop:

    bash
    # Code, code, code...
    git add .
    git commit -m "Feature finished"
  3. Merge:

    bash
    git checkout main
    git merge feature-nouvelle-fonctionnalite
    git branch -d feature-nouvelle-fonctionnalite  # Clean up

That's all! Branches = Organization and Cleanliness.

Back to table of contents