KAHIBARO
Discord Login Register

3.10. Branches and Commits

Why Branches and Commits Matter

As a backend developer, you almost never work alone or in a single straight line. You experiment, fix bugs, review code, and deploy features. Git branches and commits are the core tools that let you do all that without turning your codebase into chaos.

In this chapter you will:

You should already know what Git is and have a repository created, because those basics belong to earlier chapters.


Commits: Saving Checkpoints in Your Project

A commit is a snapshot of your project at a specific point in time. Think of it as a "save point" in a game. Every time you commit, Git stores:

All commits together form the history of your project.

Basic Commit Workflow

Typical steps when working with commits:

  1. Change some files.
  2. Stage the changes.
  3. Commit them with a message.

Step 1: Check Status

bash
git status

Example output:

text
On branch main
Changes not staged for commit:
  modified:   app.py
Untracked files:
  tests/test_app.py

This tells you:

Step 2: Stage Changes

You stage what you want to include in the next commit.

bash
# Stage a single file
git add app.py
# Stage multiple specific files
git add app.py tests/test_app.py
# Stage everything that changed
git add .

Staging lets you prepare a commit carefully. For example, you can stage only part of your work and commit it with a clear message.

Step 3: Create a Commit

bash
git commit -m "Add basic request handler for /health endpoint"

The -m flag provides a commit message.

Good commit messages are:

Examples of good messages:

Important rule
Always write meaningful commit messages. Future you, your teammates, and your reviewers will rely on them to understand why a change exists.

Viewing Commit History

See the history of commits:

bash
git log

Typical output:

text
commit 4d2b7a8c1234567890abcdef1234567890abcdef (HEAD -> main)
Author: Alice <alice@example.com>
Date:   Tue Aug 27 14:03:52 2026 +0000
    Add logging to failed login attempts
commit f1e2d3c4b5a697887766554433221100ffeeddcc
Author: Alice <alice@example.com>
Date:   Tue Aug 27 13:45:10 2026 +0000
    Implement /login endpoint

Useful variations:

bash
# More compact, one line per commit
git log --oneline
# Show a simple graph with branches
git log --oneline --graph --all

Example with graph:

text
* 4d2b7a8 Add logging to failed login attempts
* f1e2d3c Implement /login endpoint
* a1b2c3d Initial commit

Inspecting a Commit’s Changes

To see what changed in the last commit:

bash
git show

To see changes for a specific commit:

bash
git show <commit_hash>
# Example:
git show 4d2b7a8

To see just which files changed, not the full diff:

bash
git show --name-only 4d2b7a8

This is very useful during code review or debugging to understand where a bug might have been introduced.


Branches: Parallel Lines of Development

A branch is a named line of commits. The default branch in many repositories is called main or master. When you create a new branch, Git creates a new pointer to a commit, so you can add new commits there without touching other branches.

Visually:

text
main:    A --- B --- C
                      \
feature:               D --- E

Both branches share commits A, B, C, then feature has its own commits D and E.

Why branches are useful for backend work:

Creating and Switching Branches

You very rarely commit directly to main on a serious backend project. Instead, you:

  1. Create a branch from main.
  2. Work and commit in that branch.
  3. Push the branch.
  4. Open a Pull Request / Merge Request to merge back into main.

Check Which Branch You Are On

bash
git branch

Example:

text
* main
  feature/login

The * indicates the current branch.

Create a New Branch

bash
git branch feature/login

Now list again:

bash
git branch
# Output:
# * main
#   feature/login

The new branch exists, but you are still on main.

Switch to a Branch

bash
git checkout feature/login

Now feature/login is active.

You can also create AND switch in one command:

bash
git checkout -b feature/login

This is probably the most common way you will create branches.

Example: Starting a Feature Branch

Imagine you are adding a /tasks endpoint to a task management API.

bash
# Start from main
git checkout main
# Make sure main is up to date
git pull
# Create and switch to a new feature branch
git checkout -b feature/tasks-endpoint

Now all new commits will belong to feature/tasks-endpoint instead of main.


Working with Branches in Practice

Making Commits on a Branch

Once you are on a branch:

bash
# Edit files:
#   app/routes.py
#   tests/test_tasks.py
git status
# Shows modified files
git add app/routes.py tests/test_tasks.py
git commit -m "Add basic GET /tasks endpoint"

All these commits live in feature/tasks-endpoint. main is unaffected.

Listing All Branches

Local branches:

bash
git branch

Remote branches (branches that exist on the server, for example GitHub):

bash
git branch -r

Both local and remote:

bash
git branch -a

Example output:

text
* feature/tasks-endpoint
  main
  remotes/origin/main
  remotes/origin/feature/login

Pushing a Branch to Remote

To share your work or create a Pull Request:

bash
git push -u origin feature/tasks-endpoint

Next time:

bash
git push        # Now this will push feature/tasks-endpoint

Merging: Bringing Branches Together

When your feature branch is ready and reviewed, you merge it into another branch, usually main.

Basic Merge Workflow

  1. Switch to the branch you want to merge into.
  2. Run git merge <other_branch>.

Example: Merge a Feature into Main

bash
# Make sure you are on main
git checkout main
# Update main from remote
git pull
# Merge the feature branch into main
git merge feature/tasks-endpoint

If Git can combine the changes automatically, you get a fast-forward or simple merge. If both branches touched the same lines, you might get conflicts.

Fast-Forward vs Merge Commit

If main had no new commits since you created feature/tasks-endpoint, Git can "fast-forward" main to point at the same commit as feature/tasks-endpoint.

Visually before:

text
main:    A --- B
               \
feature:        C --- D

After fast-forward merge:

text
main:    A --- B --- C --- D
feature:                ^

If both branches moved independently, Git may create a merge commit that has two parents.

You do not need to fully master the difference right now. Just know:

Handling Merge Conflicts (Basic Idea)

A merge conflict happens when the same part of a file was changed differently in two branches.

Example:

When you merge, Git cannot decide which change to keep.

You will see markers in the file like:

python
<<<<<<< HEAD
def login():
    return "Login v1"
=======
def login():
    return "Login v2 with security check"
>>>>>>> feature/login

Rough conflict resolution steps:

  1. Open the file, choose or combine the correct version.
  2. Remove the <<<<<<<, =======, >>>>>>> lines.
  3. Stage the fixed file:
bash
   git add app.py
  1. Continue the merge (if Git asks) with:
bash
   git commit

Git will usually pre-fill a merge commit message.

You will get more detailed practice with conflicts in team workflows, but at this stage you should understand what conflicts are and not panic when you see them.


Comparing Branches and Commits

You often want to see what changed between two points in time.

Compare Working Directory With Last Commit

bash
git diff

Shows line by line differences for changed but not yet staged files.

Compare staged changes with last commit:

bash
git diff --cached

Compare Two Branches

bash
git diff main..feature/tasks-endpoint

This shows changes that feature/tasks-endpoint introduces compared to main.

Useful to review your own work before pushing or opening a Pull Request.

Compare Specific Commits

bash
git diff <commit1> <commit2>
# Example:
git diff a1b2c3d 4d2b7a8

Common Everyday Commands Cheat Sheet

Here is a quick table you can refer to while working:

TaskCommand example
Show current branchgit branch
Create and switch to new branchgit checkout -b feature/name
Switch to existing branchgit checkout main
See changes since last commitgit diff
Stage a filegit add app.py
Stage all changesgit add .
Commit staged changesgit commit -m "Describe change"
See history compactlygit log --oneline
Push current branch to remotegit push -u origin feature/name
Merge a branch into current branchgit merge feature/name
Delete local branch (after merge)git branch -d feature/name
Delete remote branchgit push origin --delete feature/name

Important workflow rule
For almost all team backend projects:

  • Do not commit directly to main.
  • Create a feature branch, commit there, then open a Pull Request / Merge Request to merge into main.

Example: Realistic Backend Feature Workflow

Let us walk through a full mini-scenario that mirrors real backend work.

Goal

Add a new GET /health endpoint to an existing FastAPI backend.

Step 1: Start from Latest Main

bash
git checkout main
git pull

Step 2: Create a Feature Branch

bash
git checkout -b feature/health-endpoint

Step 3: Implement the Feature

Edit app/main.py:

python
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health_check():
    return {"status": "ok"}

Step 4: Check Status and Stage Files

bash
git status
# modified: app/main.py
git add app/main.py

Step 5: Commit With a Clear Message

bash
git commit -m "Add basic GET /health endpoint"

Step 6: Push the Branch

bash
git push -u origin feature/health-endpoint

Now you can create a Pull Request on GitHub or a Merge Request on GitLab to merge feature/health-endpoint into main.

Later, after it is merged and no longer needed locally:

bash
git checkout main
git pull
git branch -d feature/health-endpoint

Good Practices for Branches and Commits

Some habits will make you a much more effective backend developer:

bash
  git checkout main
  git pull
  git checkout feature/your-branch
  git merge main

By understanding branches and commits, you now have the basic tools to:

In later chapters, you will see these tools used in more complex workflows such as pull requests, code reviews, and CI/CD pipelines, but the core mechanics you learned here remain the same.

Views: 8

Comments

Please login to add a comment.

Don't have an account? Register now!