my-notes

git_rebase_and_merge

1 min read

git rebase & merge

Combine branches using rebase or merge strategies.


πŸ”€ git merge

Merge Branch into Current

git merge feature-branch

Merges feature-branch into your current branch.


Merge with Commit Message

git merge feature-branch -m "Merge feature into main"

Merges with a custom merge commit message.


Merge with No Fast-Forward

git merge --no-ff feature-branch

Creates a merge commit even if fast-forward is possible. Preserves branch history.


Fast-Forward Only

git merge --ff-only feature-branch

Only merges if fast-forward is possible. Fails otherwise.


Squash Merge

git merge --squash feature-branch

Takes all commits from branch and squashes into one staged change. Need to commit after.


Abort Merge

git merge --abort

Cancels the merge and returns to pre-merge state.


πŸ“Š Merge Flow

gitGraph
    commit id: "A"
    commit id: "B"
    branch feature
    commit id: "C"
    commit id: "D"
    checkout main
    commit id: "E"
    merge feature id: "Merge"

πŸ”„ git rebase

Rebase Current onto Branch

git rebase main

Replays current branch's commits on top of main.


Interactive Rebase

git rebase -i HEAD~3

Opens editor to modify last 3 commits.

Options in editor:

  • pick - use commit
  • reword - edit commit message
  • edit - pause for amending
  • squash - combine with previous
  • drop - remove commit

Rebase onto Specific Commit

git rebase --onto main feature~3 feature

Rebases last 3 commits of feature onto main.


Continue After Fix

git rebase --continue

Continues rebase after resolving conflicts.


Skip Current Commit

git rebase --skip

Skips the current conflicting commit.


Abort Rebase

git rebase --abort

Cancels rebase and returns to original state.


Autosquash Fixup Commits

git rebase -i --autosquash HEAD~5

Auto-orders fixup! and squash! commits.


πŸ“Š Rebase Flow

gitGraph
    commit id: "A"
    commit id: "B"
    branch feature
    commit id: "C"
    commit id: "D"
    checkout main
    commit id: "E"

After git rebase main:

gitGraph
    commit id: "A"
    commit id: "B"
    commit id: "E"
    commit id: "C'"
    commit id: "D'"

πŸ“‹ Merge vs Rebase Comparison

Aspect Merge Rebase
History Preserves parallel Linear
Commits Adds merge commit Rewrites commits
Conflicts Once Per-commit
Safety Safe ⚠️ Rewrites history
Use case Shared branches Feature branches

⚠️ Golden Rule

Never Rebase Public Branches

Don't rebase commits that have been pushed to shared branches.


πŸ’‘ Tips

Pull with Rebase
git pull --rebase origin main
Configure Default
git config --global pull.rebase true


#git #rebase #merge #advanced

Built with mdgarden