Skip to content
notes.vinhnq.com

Search

Git, DevOps & ToolingMid20 min read

Git: branching, merge vs rebase, conflicts, reflog and the pull request flow

Review 21 cards
On this page

Git series: 1. Commits and the object model · 2. Remotes, tags and backups · 3. Branching, merge, rebase and PRs

Part 1 explained that a commit is a snapshot, a branch is just a pointer to a commit, and HEAD points at the current branch. This part builds on that for team work: merging branches, conflicts, merge or rebase, undoing work, branching strategies, the reflog and pull requests. By the end you’ll know which commands are safe on a shared branch and which belong on your own branch only.

1. Branching

Key idea: a branch gives each person an isolated context to work in parallel, and you combine the work when it’s done. Since a branch is only a pointer, creating and deleting one costs almost nothing.

The example from the slides: Dev A builds Hotel, Dev B builds Room, both committing to the same line of development, so A’s broken code breaks B’s work too.

gitGraph
  commit id: "init"
  branch feature/hotel
  checkout feature/hotel
  commit id: "hotel entity"
  checkout main
  branch feature/room
  checkout feature/room
  commit id: "room entity"
  checkout feature/hotel
  commit id: "hotel api"
  checkout main
  merge feature/hotel
  merge feature/room
git checkout -b feature/hotel     # create and switch (classic)
git switch -c feature/hotel       # modern equivalent, Git >= 2.23, clearer intent
git checkout main                 # switch branch (classic)
git switch main                   # modern
git merge feature/hotel           # merge feature/hotel INTO the current branch
git branch -d feature/hotel       # delete a merged branch

Naming branches

Key idea: name branches by the kind of work, matching the commit types: feature/, fix/, refactor/, chore/, docs/, often with a ticket id like feature/BK-123-search-by-city.

Which branch you start from (the latest release, develop or main) depends on the branching strategy, covered in section 4.

Fast-forward vs merge commit

Key idea: if the target branch hasn’t moved, Git just moves the pointer; if both sides moved on, Git creates a commit that joins them.

2. Merge conflicts

Key idea: a conflict is when Git can’t decide on its own which side wins, so you fix it by hand. Once fixed, you still have to build and run the tests.

Three typical cases:

  • Both branches changed the same lines of the same file.
  • One branch modified file X while the other deleted it (a modify/delete conflict).
  • Both branches renamed the same file to different names (rename/rename).

Git marks the conflicting region right in the file:

public BigDecimal totalPrice(Booking b) {
<<<<<<< HEAD
    return b.nightlyPrice().multiply(BigDecimal.valueOf(b.nights()));
=======
    return b.nightlyPrice().multiply(BigDecimal.valueOf(b.nights())).subtract(b.discount());
>>>>>>> feature/coupon
}

To resolve it:

  1. Open the conflicting file (git status lists it as “both modified”).
  2. Keep your side, keep their side, or combine both. Combining is often right: above, we need the discount too.
  3. Remove every marker: <<<<<<<, =======, >>>>>>>.
  4. git add <file>, then git commit (or git rebase --continue during a rebase).
  • git merge --abort / git rebase --abort gets you back to where you started.
  • Prevention beats cure: short-lived branches, integrate main often, ship big refactors in their own PR, and agree on a formatter so whitespace never causes conflicts.
Tools for resolving: zdiff3 and rerere

git rerere (reuse recorded resolution) remembers how you resolved a conflict and replays it the next time the same conflict appears.

3. Merge vs rebase

Key idea: both bring changes from one branch into another. Merge keeps history as it happened; rebase rewrites your commits into a straight line, so only do it with commits nobody else uses.

# On feature/coupon, and main has moved on
git merge main      # creates a merge commit on feature/coupon
git rebase main     # lifts feature/coupon's commits and replays them on top of main
gitGraph
  commit id: "A"
  commit id: "B"
  branch feature
  checkout feature
  commit id: "X"
  commit id: "Y"
  checkout main
  commit id: "C"
  checkout feature
  merge main id: "merge main"

A setup that works well on the teams I’ve seen:

  • While working: git pull --rebase to keep your personal feature branch current.
  • Before opening a PR: git rebase -i main to squash and tidy the commits.
  • When merging the PR: merge commit, squash and merge (one commit per PR, the most common choice with trunk-based development), or rebase and merge.

Interactive rebase, squash, cherry-pick, revert

Key idea: interactive rebase tidies commits on your own branch; cherry-pick copies one commit to another branch; revert undoes work with a new commit, which is safe on main.

  • Squash: combine several commits into one (git rebase -i HEAD~4, change pick to squash or fixup).
  • Cherry-pick: apply one commit’s change to another branch, as a new commit with a different hash. Fine for hotfixes, but not your main integration method, because it leaves duplicate-content commits on two branches.
  • Revert: add an inverse commit, without rewriting history. This is the right way to undo on main.
Commands in detail: rebase -i, fixup/autosquash, cherry-pick -x, reverting a merge commit

The slides list these as further reading, so here they are:

git rebase -i HEAD~4
# The editor opens:
# pick   1a2b3c feat(booking): add entity
# squash 4d5e6f wip            -> fold into the commit above
# fixup  7a8b9c fix typo       -> fold in, drop the message
# reword 0c1d2e add api        -> edit the message

git commit --fixup=1a2b3c         # mark this commit as a fix for 1a2b3c
git rebase -i --autosquash main   # automatically reorder and fold fixup commits

git cherry-pick 9f8e7d            # copy one commit onto the current branch (e.g. a hotfix onto a release branch)
git cherry-pick -x 9f8e7d         # add "cherry picked from ..." for traceability

git revert 9f8e7d                 # create a NEW commit that undoes 9f8e7d: safe on shared branches
git revert -m 1 <merge-commit>    # revert a merge commit, keeping the first parent

reset: three modes

Key idea: reset moves the branch pointer back, and the three modes differ in where your changes end up. Because it rewrites history, use it on your own branch only.

4. Branching strategies: Git Flow vs trunk-based

Key idea: choose by how you release. If you maintain several versions in parallel, Git Flow; if you deploy continuously with good CI, trunk-based.

gitGraph
  commit id: "v1.0" tag: "v1.0"
  branch develop
  checkout develop
  commit id: "dev"
  branch feature/search
  checkout feature/search
  commit id: "search"
  checkout develop
  merge feature/search
  branch release/1.1
  checkout release/1.1
  commit id: "bump version"
  checkout main
  merge release/1.1 tag: "v1.1"
  checkout develop
  merge release/1.1

The slides’ advice to “branch off the latest release” fits Git Flow or a release-branch model. With trunk-based development you always branch off the latest main. The pipeline that goes with trunk-based development (CI on PRs, merging to main deploys to staging, releases by tag) is in CI/CD for a Spring Boot backend.

The senior view: the DORA research (the book Accelerate) found that high-performing teams tend to use short-lived branches and integrate continuously. Git Flow isn’t “wrong”, but its costs (late merges, big conflicts, slow releases) only pay off when you must maintain several versions. When choosing, ask three questions: How often do we deploy? Do we support multiple versions at once? Are our automated tests trustworthy enough to keep main green?

5. Reflog: your safety net

Key idea: Git records every move of HEAD and of each branch, so commits “lost” to reset --hard, a deleted branch or a botched rebase can almost always be found again.

The reflog lives only on your machine and by default keeps reachable entries for about 90 days and unreachable ones for 30. It’s like browser history: you can still reopen a tab you closed.

git reflog
# 3f2a1b0 HEAD@{0}: reset: moving to HEAD~3
# 9c8d7e6 HEAD@{1}: commit: feat(booking): add cancel api
# ...

git switch -c rescue 9c8d7e6       # create a branch at the "lost" commit
# or
git reset --hard HEAD@{1}          # go back to just before the reset

git reflog show feature/coupon     # the reflog of a single branch
git branch feature/coupon <hash>   # restore a deleted branch

One more tool worth knowing: git bisect finds the commit that introduced a bug using binary search, ruling out half the commits at each step.

git bisect start
git bisect bad                 # the current commit is broken
git bisect good v1.2.0         # this tag still worked
git bisect run ./mvnw -q test -Dtest=BookingPriceTest   # run the test automatically at each step
git bisect reset

6. The code review flow with pull requests

Key idea: every change to main goes through a small PR with green CI and at least one approval. Reviewers focus on design and correctness and leave style to the tools.

sequenceDiagram
  participant Dev
  participant GH as GitHub
  participant CI
  participant Rev as Reviewer
  Dev->>Dev: git switch -c feature/BK-42-cancel-booking
  Dev->>GH: git push -u origin feature/BK-42-cancel-booking
  Dev->>GH: Open a pull request (context, how to test, screenshots/logs)
  GH->>CI: Build, test, lint, security scan
  CI-->>GH: Result (must be green)
  Rev->>GH: Review and comment
  Dev->>GH: Push follow-up (or fixup) commits
  Rev->>GH: Approve
  GH->>GH: Squash/merge into main, delete the branch

The two habits that matter most: keep PRs small (ideally under 400 changed lines) and review your own diff before asking anyone else.

Checklist for PR authors and reviewers, and GitHub protections

As the PR author:

  • Keep PRs small (ideally under 400 changed lines). Huge PRs get rubber-stamped.
  • Describe the problem, the solution, why this approach, how you tested it, and the risks.
  • Review your own diff before asking anyone else.
  • Put pure refactoring and behaviour changes in separate PRs.

As the reviewer, in priority order:

  1. Design and correctness: does it solve the right problem? Edge cases, concurrency, transactions.
  2. Security and data: input validation, authorisation, secrets, migration safety (does it lock a table? can it be rolled back?).
  3. Tests: is the new behaviour and the fixed bug covered?
  4. Readability and naming.
  5. Style: let the formatter and linter handle it, don’t spend human time on it.

Protections on GitHub: branch protection on main (no direct pushes, PR required, CI must pass, at least one approval) and a CODEOWNERS file to auto-assign reviewers by directory.

Exercises

Task (paraphrased): Create a GitHub repo for your course homework. Each lesson gets its own branch (for example “operators and conditions”, “arrays, strings, I/O”). From each lesson branch, create a child branch per exercise, put the code there, then merge the exercise branches back into their lesson branch.

Hint: don’t name the exercise branch <lesson branch>/01, because Git won’t let branches a/b and a/b/c coexist (see the solution).

Solution: a homework repo with lesson and exercise branches
mkdir f01-homework && cd f01-homework
git init -b main
cat > .gitignore <<'EOF'
target/
out/
*.class
.idea/
*.iml
.DS_Store
EOF
echo "# Homework - Fundamentals of Backend" > README.md
git add .gitignore README.md
git commit -m "chore: init repository"

gh repo create f01-homework --private --source=. --remote=origin --push
# or create it on the web, then: git remote add origin <url> && git push -u origin main

# --- Lesson 03 ---
git switch -c lesson/03-operators-conditions main
git push -u origin lesson/03-operators-conditions

git switch -c exercise/03-operators-conditions/01 lesson/03-operators-conditions
mkdir -p lesson03 && cp ~/old-code/lesson03/Ex01.java lesson03/
git add lesson03/Ex01.java
git commit -m "feat(lesson03): add exercise 01 - classify triangle"
git push -u origin exercise/03-operators-conditions/01

git switch lesson/03-operators-conditions
git merge --no-ff exercise/03-operators-conditions/01 -m "merge exercise 03/01 into lesson 03"
git push

# --- Lesson 05: repeat with exercise/05-arrays-text-io/02 ---
git switch -c lesson/05-arrays-text-io main
git switch -c exercise/05-arrays-text-io/02
# ... copy code, add, commit, push, switch back to the lesson branch, merge --no-ff

git log --oneline --graph --all     # check the structure

Why it’s done this way:

  • --no-ff keeps a merge commit, so git log --graph clearly shows which exercise went into which lesson, which is the point of the exercise.
  • In real life, the merge step should go through a pull request on GitHub (exercise → lesson) so you practise the review flow instead of merging locally.
  • The .gitignore is in the very first commit, so no .class files or IDE settings slip in.

Bonus drill (my own): practise conflicts and the reflog: create two branches that edit the same line, merge both into main, resolve, then “accidentally” reset --hard and recover.

Bonus drill solution: conflicts and the reflog
git switch -c a main && echo "price = 100" > p.txt && git add p.txt && git commit -m "a"
git switch -c b main && echo "price = 120" > p.txt && git add p.txt && git commit -m "b"
git switch main && git merge a && git merge b        # conflict in p.txt
# edit p.txt, remove markers, git add p.txt, git commit
git reset --hard HEAD~2                              # "oops"
git reflog                                           # find the merge commit hash
git reset --hard HEAD@{1}                            # recovered

Remember

  • Can you explain when a merge is a fast-forward, when Git creates a merge commit, and what --no-ff is for?
  • Do you know when rebasing is safe, when it isn’t, and why --force-with-lease beats --force?
  • Can you choose between reset and revert, and name the three modes of reset?
  • Can you argue for Git Flow or trunk-based for a team based on deploy frequency, number of versions and test trust?
  • Can you recover commits with the reflog, state its limit, and find a bad commit with git bisect?

Interview questions

Junior

When does a merge conflict happen and how do you resolve it?

When Git can’t decide which side is right: both branches changed the same lines, or one side edited a file the other deleted or renamed.

Open the file, keep one side or combine them, remove the <<<<<<< ======= >>>>>>> markers, git add, then commit (or rebase --continue). Then build and run the tests, because a resolution can be syntactically fine but logically wrong.

What is a fast-forward merge? When does Git create a merge commit?

A fast-forward is when Git just moves the target branch’s pointer forward with no new commit; a merge commit appears when both branches have new commits.

If the target branch has no new commits since the feature branch was created, Git moves its pointer to the feature branch’s last commit. If both moved on, Git does a three-way merge using the merge base and creates a merge commit with two parents. git merge --no-ff forces a merge commit even when a fast-forward is possible, to keep a visible trace of the feature.

Mid

Merge vs rebase: what’s the difference and when do you use each?

Merge preserves history with a merge commit; rebase replays your commits on top of the target branch, giving new hashes and a linear history.

I rebase personal, unshared branches (to catch up with main or tidy commits before a PR) and merge, or squash-merge through a PR, into shared branches. Never rebase commits other people have built on.

revert vs reset?

reset rewrites history and is only safe on your own branch; revert adds an inverse commit and is safe on shared branches.

reset moves the branch pointer back to an older commit. revert adds a new commit that undoes an earlier one without touching existing history, so it’s fine on main.

How is –force-with-lease different from –force?

--force overwrites the remote no matter what’s there; --force-with-lease refuses if the remote has commits you haven’t seen.

--force-with-lease only overwrites if the remote is still at the commit you last saw, according to your remote-tracking branch (your local copy of the remote branch). If a teammate pushed in the meantime, it refuses, so you don’t wipe out their work.

What are the pros and cons of squash merging?

Pros: one commit per PR, a clean history, and a whole feature reverts in one go. Cons: you lose the small commits inside, and you get repeated conflicts if the feature branch keeps being used.

Losing the fine-grained commits makes it harder to bisect within the PR. If the feature branch keeps being used after the squash, Git doesn’t recognise its commits as merged, which leads to repeated conflicts.

When would you cherry-pick, and what are the risks?

When you need one specific commit on another branch without merging the whole branch, classically backporting a hotfix from main to an older release branch.

Risks: you get duplicate-content commits with different hashes on two branches, which can conflict when those branches later merge. The picked commit may also depend on other commits the target branch doesn’t have. Use -x to record where it came from.

Senior

You ran reset –hard and lost three commits, or deleted an unmerged branch. How do you recover?

Use git reflog to find the hash from before the reset (or the deleted branch’s last commit), then create a branch there or reset to it.

Commands: git branch rescue <hash> or git reset --hard HEAD@{n}. The commits stay in the object database until gc (garbage collection), roughly 30 to 90 days by default. Changes that were never staged or committed can’t be recovered through the reflog.

Git Flow or trunk-based? How would you choose for a team?

It depends on how you release: several versions in parallel points to Git Flow, continuous deployment with strong CI points to trunk-based.

  • Git Flow suits versioned products (mobile apps, libraries, on-prem), at the cost of late integration and big conflicts.
  • Trunk-based suits continuously deployed web services: short-lived branches, an always-deployable main, unfinished work behind feature flags. It requires fast CI, trustworthy automated tests and quick reviews.
  • I look at deploy frequency, how many versions we maintain, and test maturity, and I usually lean towards trunk-based plus a release branch when we need to hotfix older versions.
How do you find which of the last 500 commits introduced a regression?

Use git bisect: a binary search between one good and one bad commit, about log2(500) ≈ 9 steps.

At each step you, or a script via git bisect run, say whether the commit is good or bad, and Git halves the remaining range. It only works well if every commit builds and can be tested, which is exactly why commit hygiene matters.

Useful phrases for interviews

  • “I rebase my own branch to keep it up to date, but I never rewrite history that’s already shared.”
  • “On a shared branch I’d rather revert than reset, because revert doesn’t rewrite history.”
  • “Our team follows trunk-based development: branches live a day or two, and unfinished features stay behind flags.”
  • “After resolving a conflict, I rebuild and rerun the tests, because a clean merge can still be logically broken.”
  • “If I lose commits, the first thing I check is the reflog.”
  • “I’d use force-with-lease rather than a plain force push, so I can’t overwrite a teammate’s commits.”
  • “Git bisect found the offending commit in about ten steps, because every commit on main builds.”
  • “We squash-merge pull requests, so each feature lands as a single commit that’s easy to revert.”

Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words.