Git - Merging

Git - Merging

Merging in Git

In Git, merging is the process of integrating changes from one branch into another. Merging allows developers to combine separate lines of development, enabling collaborative workflows and parallel development efforts. This document explores Git merging in depth, including merge types, conflict resolution, strategies, and best practices.

What is Git Merging?

When you create a new branch and make changes, Git keeps the history of those changes separately. At some point, you may want to combine the work from two branches. Git merge helps you do that. The most common scenario is merging a feature branch back into the main branch.

Basic Git Merge

Step-by-Step Merge

git checkout main
git merge feature-branch

This merges the feature-branch into main. If there are no conflicting changes, Git completes the merge automatically and creates a new merge commit.

Example Scenario

git checkout -b feature
# make some changes
git add .
git commit -m "Add new feature"

git checkout main
git merge feature

Types of Merges

Fast-Forward Merge

Occurs when the target branch has not diverged from the source. Git simply moves the pointer forward.

git checkout main
git merge feature

Non Fast-Forward Merge

Occurs when both branches have new commits. Git creates a new merge commit with both sets of changes.

Three-Way Merge

Uses three snapshots to generate the merge commit: the two branch tips and their common ancestor.

Fast-Forward Merge Example

Create Branch and Commit

git checkout -b fast-forward
echo "Hello" > hello.txt
git add hello.txt
git commit -m "Add hello.txt"

git checkout main
git merge fast-forward

This results in a fast-forward merge.

Recursive Merge (Three-Way)

Diverging Branch Example

git checkout -b feature
echo "Feature A" > file.txt
git commit -am "Feature A"

git checkout main
echo "Main update" > file.txt
git commit -am "Main changes"

git merge feature

This will create a merge commit using a three-way merge strategy.

Git Merge Commit

After a non-fast-forward merge, Git creates a special merge commit containing metadata from both parent commits.

View Merge Commit

git log --graph --oneline

Example Output

*   9b3c442 Merge branch 'feature'
|\
| * 56acfea Feature work
* | b79e3f4 Main work
|/

Merge Conflict Overview

A merge conflict happens when Git cannot automatically reconcile differences between branches.

Common Conflict Scenario

# On main
echo "Line 1" > notes.txt
git commit -am "Main: Line 1"

# On feature
git checkout -b feature
echo "Different Line 1" > notes.txt
git commit -am "Feature: Line 1"

# Merge
git checkout main
git merge feature

Conflict Output

Auto-merging notes.txt
CONFLICT (content): Merge conflict in notes.txt
Automatic merge failed; fix conflicts and then commit the result.

Resolving Merge Conflicts

View Conflicted Files

git status

Conflict Markers in Files

<<<<<<< HEAD
Line from main
=======
Line from feature
>>>>>>> feature

Steps to Resolve

1. Edit the file to fix the conflict 2. Remove conflict markers 3. Stage the file 4. Commit the merge

Command

git add notes.txt
git commit -m "Resolve conflict in notes.txt"

Using Merge Tools

Set Up a Merge Tool

git config --global merge.tool meld

Invoke Merge Tool

git mergetool

Abort Merge

git merge --abort

Merge Strategies

Default: Recursive

git merge feature

Ours Strategy (Ignore other changes)

git merge -s ours feature

Octopus Strategy (Multiple branches)

git merge branch1 branch2 branch3

Useful for merging more than two heads. Limited to trivial merges.

Squash Merging

Squash merge combines all commits from a branch into a single commit.

Command

git checkout main
git merge --squash feature

Then Commit

git commit -m "Squash merge of feature branch"

Note: Squash does not preserve individual commit history.

Rebase vs Merge

While merging preserves full history, rebasing rewrites history to create a linear timeline.

Rebase Example

git checkout feature
git rebase main

After rebasing, you can use fast-forward merge back to main.

Merging Remote Changes

Pull with Merge

git pull origin main

This fetches and merges changes from the remote repository.

Disable Auto-Merge on Pull

git config pull.rebase true

Merge Hooks

Git provides hooks like pre-merge-commit and post-merge to automate tasks.

Create a Hook

echo "echo 'Merge complete'" > .git/hooks/post-merge
chmod +x .git/hooks/post-merge

Undo a Merge

If Merge Not Committed

git merge --abort

After Commit

git reset --hard HEAD~1

Best Practices for Merging

  • Pull latest changes before starting a merge
  • Keep feature branches short-lived to reduce conflicts
  • Use squash for small or temporary branches
  • Use descriptive commit messages on merge commits
  • Resolve conflicts manually with care
  • Test the code after merging
  • Use tools like GitHub or GitLab’s UI for safer merges

Advanced Merge Scenarios

Merge Specific Commit

git cherry-pick abc123

Merge Without Committing

git merge --no-commit feature

Merge Without Fast-Forward

git merge --no-ff feature

This forces a merge commit even when fast-forward is possible.

Merge Tools Comparison

  • Meld: User-friendly GUI
  • KDiff3: Detailed diff view
  • VSCode: Can act as mergetool

Set VSCode as Merge Tool

git config --global merge.tool vscode
git config --global mergetool.vscode.cmd "code --wait $MERGED"

Common Merge Mistakes

  • Forgetting to pull before merging
  • Using merge in place of rebase (or vice versa) in the wrong context
  • Ignoring or incorrectly resolving conflicts
  • Force pushing merged changes without review

Merging is an essential part of Git's collaborative workflow. Whether working solo or in a team, understanding how Git merge works, how to resolve conflicts, and how to apply different strategies is vital to managing code efficiently. From simple fast-forward merges to complex three-way recursive strategies, Git offers the tools needed to keep your project integrated and stable. Following best practices and learning to use Git’s merge features effectively will result in a cleaner, more maintainable project history and smoother team collaboration.

Beginner 5 Hours
Git - Merging

Merging in Git

In Git, merging is the process of integrating changes from one branch into another. Merging allows developers to combine separate lines of development, enabling collaborative workflows and parallel development efforts. This document explores Git merging in depth, including merge types, conflict resolution, strategies, and best practices.

What is Git Merging?

When you create a new branch and make changes, Git keeps the history of those changes separately. At some point, you may want to combine the work from two branches. Git merge helps you do that. The most common scenario is merging a feature branch back into the main branch.

Basic Git Merge

Step-by-Step Merge

git checkout main git merge feature-branch

This merges the feature-branch into main. If there are no conflicting changes, Git completes the merge automatically and creates a new merge commit.

Example Scenario

git checkout -b feature # make some changes git add . git commit -m "Add new feature" git checkout main git merge feature

Types of Merges

Fast-Forward Merge

Occurs when the target branch has not diverged from the source. Git simply moves the pointer forward.

git checkout main git merge feature

Non Fast-Forward Merge

Occurs when both branches have new commits. Git creates a new merge commit with both sets of changes.

Three-Way Merge

Uses three snapshots to generate the merge commit: the two branch tips and their common ancestor.

Fast-Forward Merge Example

Create Branch and Commit

git checkout -b fast-forward echo "Hello" > hello.txt git add hello.txt git commit -m "Add hello.txt" git checkout main git merge fast-forward

This results in a fast-forward merge.

Recursive Merge (Three-Way)

Diverging Branch Example

git checkout -b feature echo "Feature A" > file.txt git commit -am "Feature A" git checkout main echo "Main update" > file.txt git commit -am "Main changes" git merge feature

This will create a merge commit using a three-way merge strategy.

Git Merge Commit

After a non-fast-forward merge, Git creates a special merge commit containing metadata from both parent commits.

View Merge Commit

git log --graph --oneline

Example Output

* 9b3c442 Merge branch 'feature' |\ | * 56acfea Feature work * | b79e3f4 Main work |/

Merge Conflict Overview

A merge conflict happens when Git cannot automatically reconcile differences between branches.

Common Conflict Scenario

# On main echo "Line 1" > notes.txt git commit -am "Main: Line 1" # On feature git checkout -b feature echo "Different Line 1" > notes.txt git commit -am "Feature: Line 1" # Merge git checkout main git merge feature

Conflict Output

Auto-merging notes.txt CONFLICT (content): Merge conflict in notes.txt Automatic merge failed; fix conflicts and then commit the result.

Resolving Merge Conflicts

View Conflicted Files

git status

Conflict Markers in Files

<<<<<<< HEAD Line from main ======= Line from feature >>>>>>> feature

Steps to Resolve

1. Edit the file to fix the conflict 2. Remove conflict markers 3. Stage the file 4. Commit the merge

Command

git add notes.txt git commit -m "Resolve conflict in notes.txt"

Using Merge Tools

Set Up a Merge Tool

git config --global merge.tool meld

Invoke Merge Tool

git mergetool

Abort Merge

git merge --abort

Merge Strategies

Default: Recursive

git merge feature

Ours Strategy (Ignore other changes)

git merge -s ours feature

Octopus Strategy (Multiple branches)

git merge branch1 branch2 branch3

Useful for merging more than two heads. Limited to trivial merges.

Squash Merging

Squash merge combines all commits from a branch into a single commit.

Command

git checkout main git merge --squash feature

Then Commit

git commit -m "Squash merge of feature branch"

Note: Squash does not preserve individual commit history.

Rebase vs Merge

While merging preserves full history, rebasing rewrites history to create a linear timeline.

Rebase Example

git checkout feature git rebase main

After rebasing, you can use fast-forward merge back to main.

Merging Remote Changes

Pull with Merge

git pull origin main

This fetches and merges changes from the remote repository.

Disable Auto-Merge on Pull

git config pull.rebase true

Merge Hooks

Git provides hooks like pre-merge-commit and post-merge to automate tasks.

Create a Hook

echo "echo 'Merge complete'" > .git/hooks/post-merge chmod +x .git/hooks/post-merge

Undo a Merge

If Merge Not Committed

git merge --abort

After Commit

git reset --hard HEAD~1

Best Practices for Merging

  • Pull latest changes before starting a merge
  • Keep feature branches short-lived to reduce conflicts
  • Use squash for small or temporary branches
  • Use descriptive commit messages on merge commits
  • Resolve conflicts manually with care
  • Test the code after merging
  • Use tools like GitHub or GitLab’s UI for safer merges

Advanced Merge Scenarios

Merge Specific Commit

git cherry-pick abc123

Merge Without Committing

git merge --no-commit feature

Merge Without Fast-Forward

git merge --no-ff feature

This forces a merge commit even when fast-forward is possible.

Merge Tools Comparison

  • Meld: User-friendly GUI
  • KDiff3: Detailed diff view
  • VSCode: Can act as mergetool

Set VSCode as Merge Tool

git config --global merge.tool vscode git config --global mergetool.vscode.cmd "code --wait $MERGED"

Common Merge Mistakes

  • Forgetting to pull before merging
  • Using merge in place of rebase (or vice versa) in the wrong context
  • Ignoring or incorrectly resolving conflicts
  • Force pushing merged changes without review

Merging is an essential part of Git's collaborative workflow. Whether working solo or in a team, understanding how Git merge works, how to resolve conflicts, and how to apply different strategies is vital to managing code efficiently. From simple fast-forward merges to complex three-way recursive strategies, Git offers the tools needed to keep your project integrated and stable. Following best practices and learning to use Git’s merge features effectively will result in a cleaner, more maintainable project history and smoother team collaboration.

Related Tutorials

Frequently Asked Questions for GitHub

Teams use GitHub for version control, code sharing, pull requests, and project management.

SSH allows secure communication with GitHub for pushing and pulling code without passwords.

A release marks a specific version of code, often used for deployments or tagging milestones.

Git is a distributed version control system for tracking changes in source code efficiently.

It shows the current state of the repository, including staged, unstaged, and untracked files.


GitHub Pages hosts static websites directly from a GitHub repository.

Git is a tool; GitHub is a platform using Git for remote code collaboration.

Use git revert <commit> to undo changes by creating a new commit.

git commit saves staged changes to the local repository with a message.


Issues track bugs, tasks, or feature requests, allowing discussion and assignment.

Merging combines changes from different branches into one branch, typically main or master.


git push uploads local repository changes to a remote repository like GitHub.

GitHub Actions automates workflows like building, testing, and deploying code with CI/CD pipelines.

.gitignore specifies files and directories Git should ignore and not track.

git init initializes a new Git repository in your local project directory.

git add stages changes in files for the next commit.

A pull request proposes changes from one branch to another, usually for review and merge.

A branch allows parallel development by creating independent code versions from the main project.

GitHub is a cloud-based platform for hosting and managing Git repositories collaboratively.

The default branch name is usually main, previously known as master.

Cloning downloads a copy of a GitHub repository to your local machine.

git pull fetches and merges changes from a remote repository to your local branch.

A commit records a snapshot of file changes with a message and unique ID.

A repository stores project files, folders, and version history for collaborative development.

A fork creates a personal copy of another user's repository for independent development.


A GitHub milestone is a way to track progress on a specific goal or release by grouping related issues and pull requests.

To merge a pull request, review the proposed changes and click "Merge pull request" to integrate them into the base branch.

GitHub labels are tags that help categorize and prioritize issues and pull requests, making it easier to manage and filter them.​

To create a GitHub issue, navigate to the "Issues" tab of your repository and click "New issue."

After making changes in your forked repository, navigate to the original repository and click "New pull request" to propose your changes.

A merge conflict occurs when GitHub cannot automatically merge changes due to conflicting modifications in the same part of a file.​

To use GitHub Actions, create a YAML file in the .github/workflows directory of your repository to define your workflow.

To resolve a merge conflict, manually edit the conflicting files to combine changes, then commit the resolved files.

A branch in GitHub is a parallel version of a repository, allowing you to work on different features or fixes without affecting the main codebase.​

To add a collaborator, go to your repository's settings, select "Collaborators," and enter the GitHub username of the person you want to add.​

A GitHub Gist is a simple way to share code snippets or text, useful for sharing small pieces of code or notes.

A fork creates a personal copy of someone else's repository, allowing you to propose changes. A clone creates a local copy of a repository on your machine.​

To create a GitHub repository, log in to your GitHub account, click the "+" icon in the top right corner, and select "New repository."

To set up GitHub Pages, navigate to your repository's settings, scroll to the "GitHub Pages" section, and select the source branch.

To create a GitHub Gist, log in to your GitHub account, click the "+" icon, and select "New Gist."

A GitHub organization is a shared account where multiple people can collaborate on repositories, issues, and other GitHub features.​

The GitHub CLI is a command-line interface that allows you to interact with GitHub directly from your terminal, enabling operations like creating issues and pull requests.

o use GitHub Copilot, install the extension in a supported IDE, such as Visual Studio Code, and start typing code to receive suggestions.

To create a GitHub organization, click your profile picture in the top right corner, select "Your organizations," and click "New organization."

GitHub Copilot is an AI-powered code completion tool developed by GitHub in collaboration with OpenAI, providing suggestions as you code.​

GitHub is a web-based platform for version control and collaboration, allowing developers to host and review code, manage projects, and build software together.​

To install the GitHub CLI, download the appropriate version for your operating system from the official GitHub CLI website and follow the installation instructions.

line

Copyrights © 2024 letsupdateskills All rights reserved