Git & GitHub: Merging


Understanding Git Merge

Branching lets you work independently, but eventually, you'll need to combine these changes into other branches—this process is known as merging.

  • Git merges entire branches, not individual commits.
  • All merges happen into your current branch (where HEAD points).

How to Merge Branches

Basic Merge Steps:

  1. Switch to the receiving branch (the branch you want to merge changes into).
  2. Merge the target branch into your current branch using git merge.

Example: Merge the bugfix branch into master:

git switch master
git merge bugfix

Merge Types

When you merge branches in Git, the result can be represented in different ways depending on the relationship between the branches and the merge method used.


1. Fast-Forward Merge

A fast-forward merge occurs when the receiving branch has not progressed since the feature branch diverged. Git simply moves the branch pointer forward.

  • No merge commit is created.
  • Keeps history linear and clean.
  • Often used when there's no other work on the base branch.

Use case: Merging a short-lived feature branch directly into mainline with no intermediate commits on main.

Example:

Before:
A---B---C  (main)
         \
          D---E  (feature)

After merge:
A---B---C---D---E  (main)

Command:

git switch main
git merge feature

2. Merge Commit (Non-Fast Forward)

Occurs when both branches have diverged—i.e., the base branch has new commits and the feature branch has commits too.

  • Git creates a new commit with two parents to record the merge.
  • Useful in collaborative environments to preserve full history.
  • Helps clarify the context of combining two branches.

Use case: Team projects where branch history matters.

Example:

Before:
A---B---C       (main)
         \
          D---E  (feature)

After merge:
A---B---C-------F  (main)
         \     /
          D---E

Where F is the merge commit.

Command:

git switch main
git merge feature

3. Rebase Merge

Instead of merging, you can rebase a feature branch onto the latest main branch.

  • Rewrites commit history by placing commits on top of the base.
  • Keeps linear history and avoids merge commits.
  • Should only be used with local or private branches to avoid confusion.

Use case: Cleaning up commit history before merging.

Example:

git switch feature
git rebase main

This replays the feature commits on top of main.


4. Squash Merge

Combines all commits from a feature branch into a single commit on the base branch.

  • Clean, concise history.
  • Often used for merging long-lived feature branches with lots of commits.

Use case: Collapsing a noisy commit trail into one meaningful commit.

Command:

git switch main
git merge --squash feature
git commit -m "Add login feature"

Example:

Original:
A---B---C       (main)
         \
          D---E---F  (feature)

After squash:
A---B---C---G  (main)

Where G is a single commit combining D, E, and F.