Skip to content

Git Deep Dive & Branching Strategies

What you’ll learn. Git’s data model (blobs, trees, commits, refs) so its commands stop feeling like magic; the real difference between merge and rebase; how branching strategies (trunk-based, GitHub Flow, GitFlow) trade off against delivery speed; monorepo considerations; hooks; commit signing; and a recovery playbook using the reflog. This is the foundation for CI/CD and GitOps.

Git is a content-addressable object store with a thin layer of named pointers. Everything is one of four object types, each identified by a hash (SHA-1 traditionally, SHA-256 in newer repositories) of its content:

  • blob: file contents (no name, no metadata).
  • tree: a directory listing mapping names and modes to blobs or other trees.
  • commit: a pointer to a root tree, zero or more parent commits, author, committer, timestamp, and message.
  • tag (annotated): a named, optionally signed pointer to another object.
commit c3 ──parent──> commit c2 ──parent──> commit c1
│ │
▼ ▼
tree t3 tree t2
├─ README (blob b1) ├─ README (blob b1) <- same blob, stored once
└─ src/ (tree) └─ src/ (tree)

Because identical content hashes identically, unchanged files and directories are shared across commits. A commit is therefore a snapshot, not a diff; diffs are computed on demand. History is a directed acyclic graph (DAG) of commits, and any change to a commit (content, parent, message) changes its hash, so “rewriting history” means creating new commits.

Inspect it directly:

Terminal window
git init demo && cd demo
echo hello > a.txt && git add a.txt && git commit -m "first"
git cat-file -t HEAD # commit
git cat-file -p HEAD # shows tree, author, message
git cat-file -p 'HEAD^{tree}' # lists blobs
git rev-parse HEAD
git count-objects -vH

A ref is a file containing a hash (or a symbolic ref). Branches are refs/heads/<name>, remote-tracking branches are refs/remotes/origin/<name>, tags are refs/tags/<name>. HEAD is usually a symbolic ref pointing to the current branch. A branch is just a 41-byte file; creating one is free.

Terminal window
cat .git/HEAD # ref: refs/heads/main
cat .git/refs/heads/main # the commit hash
git branch feature # writes a new ref file

Committing moves the current branch ref forward. Detached HEAD means HEAD points directly at a commit; new commits are not on any branch and can be lost (they remain reachable only through the reflog until garbage collection).

Git has three areas: the working tree (files on disk), the index/staging area (the proposed next commit), and HEAD (last commit). git add copies working tree to index, git commit writes the index as a tree and a commit. git restore --staged and git restore move data the other way. git reset has modes that choose how far back to move: --soft moves only the branch ref; --mixed (default) also resets the index; --hard also overwrites the working tree (destructive for uncommitted changes).

Packfiles compress many objects using delta encoding; git gc repacks. You rarely need to think about it, except in monorepos and when a large binary has been committed (it lives in history forever unless you rewrite it).

Both integrate changes from one branch into another. They differ in the shape of history.

Before: main: A---B---C
\
feature: D---E
merge: A---B---C-------M (M has two parents: C and E)
\ /
D-------E
rebase: A---B---C---D'---E' (D, E replayed as new commits)

Merge creates a merge commit with two parents, preserving the true history. Rebase replays your commits on top of the target, creating new commits (D’, E’) with new hashes and a linear history. Squash merge collapses the branch to one commit on the target.

Terminal window
git switch feature
git fetch origin
git rebase origin/main # replay feature onto latest main
git rebase -i origin/main # interactive: reorder, squash, fixup, reword, drop
git push --force-with-lease # safe force push after rebasing a branch only you use
git switch main
git merge --no-ff feature # always create a merge commit
git merge --squash feature && git commit

The golden rule: do not rebase commits that others have based work on (published, shared branches), because their copies of the old commits diverge from yours. Rebase your own unpublished/feature branches freely. Use --force-with-lease rather than --force: it refuses to overwrite remote commits you have not seen.

Trade-offs:

Merge Rebase / squash
History Faithful, with merge bubbles Linear, readable
git bisect, git revert Reverting a merge needs -m 1 Straightforward
Conflict handling Resolve once Resolve per replayed commit (rebase)
Risk Low Rewrites hashes; mistakes are recoverable but confusing

Many teams choose “squash merge PRs into main” for a clean one-commit-per-change history with the PR as the unit of review. Whatever you pick, pick one and enforce it with repository settings.

A conflict arises when both sides changed the same region relative to their merge base (common ancestor). Git is a three-way merge: base, ours, theirs.

<<<<<<< HEAD
timeout = 30
=======
timeout = 60
>>>>>>> feature

Resolve, git add, then git rebase --continue (or commit for a merge). Enable git config rerere.enabled true to record and replay resolutions, and merge.conflictStyle zdiff3 to show the base version, which makes resolving far easier.

Everyone integrates into a single branch (main/trunk) at least daily, using very short-lived branches (hours to a day or two) or committing directly. Incomplete features are hidden behind feature flags (CI/CD); releases are cut from trunk (tag, or a short-lived release branch for hotfixes).

Why it wins in the DORA research: small batches, constant integration, no long-lived-branch merge pain, and CI that runs against what actually ships. Requirements: fast, reliable CI; good test coverage; feature flags; code review that completes quickly (or pair/mob programming); branch protection.

A simplified variant: main is always deployable; work on a short-lived feature branch; open a pull request; review and CI; merge; deploy. Close to TBD when branches stay short.

Vincent Driessen’s 2010 model uses long-lived main and develop branches plus feature/*, release/*, and hotfix/* branches. It fits versioned, packaged software with multiple supported releases (desktop apps, firmware, libraries with maintenance branches). For web services deployed continuously it adds ceremony and delays integration: features sit on branches, then “integration hell” at release time. Driessen himself later noted it is not a fit for continuously delivered software.

Trunk-based GitHub Flow GitFlow
Long-lived branches 1 1 2+
Typical branch lifetime hours days weeks
Release mechanism tag/deploy from trunk deploy on merge release branch
Fits continuous delivery, SaaS most web teams multiple supported versions
Needs flags, strong CI strong CI release management

For maintaining several versions, a lighter pattern than GitFlow: trunk plus release branches (release/1.4) created at release time, with fixes cherry-picked (git cherry-pick -x <sha>) from trunk.

Atomic commits (one logical change, builds and tests pass), imperative subject under about 50-72 characters, body explaining why. Conventional Commits (feat:, fix:, chore:, feat!: for breaking) enable automated changelogs and semantic versioning (semantic-release, release-please). Keep PRs small: review quality drops sharply with size.

Monorepo Polyrepo
Atomic cross-project changes Yes Needs coordinated PRs/versions
Shared tooling and versions Easy to unify Drift
CI cost Needs affected-only builds Natural isolation
Access control Coarse unless using CODEOWNERS/path rules Per repo
Scale limit Needs build tooling and Git features Many repos to manage

Monorepos (Google, Meta, many modern TypeScript shops) require investment: build systems with caching and dependency graphs (Bazel, Nx, Turborepo, Pants), CODEOWNERS, path-filtered CI (on.push.paths), and Git features for scale: git sparse-checkout, partial clone (--filter=blob:none), and git maintenance/fsmonitor. Neither choice is universally right; the failure mode is a monorepo without affected-only CI, where every commit builds everything.

Hooks are scripts Git runs at points in its workflow, stored in .git/hooks (not versioned). Client-side: pre-commit, commit-msg, pre-push. Server-side: pre-receive, update. To share hooks, use core.hooksPath pointing to a versioned directory, or a framework such as pre-commit or Husky/lefthook.

#!/usr/bin/env bash
# .githooks/commit-msg: enforce a Conventional Commits subject
set -euo pipefail
subject=$(head -1 "$1")
re='^(feat|fix|docs|chore|refactor|test|ci|build|perf)(\([a-z0-9-]+\))?!?: .{1,72}$'
[[ $subject =~ $re ]] || { echo "commit subject must match Conventional Commits" >&2; exit 1; }
Terminal window
git config core.hooksPath .githooks
chmod +x .githooks/commit-msg

Local hooks are bypassable (--no-verify), so treat them as developer convenience and enforce the same checks in CI and branch protection.

A commit’s author field is just text; anyone can claim to be you. Signing cryptographically binds a commit to a key, and hosting platforms display “Verified”.

Modern, simple option: sign with an SSH key.

Terminal window
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
git config --global tag.gpgsign true
# verify locally: map allowed signers
echo "you@example.com $(cat ~/.ssh/id_ed25519.pub)" > ~/.config/git/allowed_signers
git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
git log --show-signature -1

GPG remains supported; Sigstore gitsign gives keyless signing using OIDC identities (see DevSecOps). Combine signing with branch protection (“require signed commits”) for supply-chain assurance.

Terminal window
git log --oneline --graph --decorate --all
git log -S'needle' # pickaxe: commits that added/removed a string
git log -L :funcname:file.py # history of a function
git blame -w -C file.py # ignore whitespace, detect moved lines
git bisect start; git bisect bad; git bisect good v1.2.0
git bisect run ./test.sh # automatic binary search for the breaking commit
git worktree add ../hotfix main # second checkout without cloning
git stash push -m "wip" -u
git diff --stat main...HEAD # three-dot: changes since merge base
git range-diff old..new # compare two versions of a rebased series

git bisect run is a superpower: with nn commits it finds the culprit in about ⌈log⁡2n⌉\lceil \log_2 n \rceil steps, so 1000 commits take 10 test runs.

Git rarely destroys committed work immediately. Key idea: the reflog records every position HEAD and each branch has been at (local only, default retention about 90 days for reachable and 30 days for unreachable entries).

Mistake Fix
Committed to the wrong branch git branch correct-branch; git reset --hard HEAD~1 (on wrong branch), then switch
Bad last commit message / forgot a file git commit --amend (unpushed)
Want to undo a pushed commit git revert <sha> (new inverse commit; safe for shared history)
Reset —hard too far git reflog, find the old hash, git reset --hard <hash>
Rebase went wrong git rebase --abort, or git reflog and reset to ORIG_HEAD/the pre-rebase entry
Deleted a branch git reflog, then git branch name <hash>
Lost a stash git fsck --unreachable | grep commit
Merge is a mess git merge --abort
Committed a secret Rotate the secret first. Then rewrite history with git filter-repo; assume it is compromised regardless
Need one file from another commit git restore --source=<sha> -- path
Terminal window
git reflog
# 3f2a1b9 HEAD@{0}: reset: moving to HEAD~3
# a91c4de HEAD@{1}: commit: add retry logic <- what you want
git reset --hard a91c4de

Branch protection (require PR, required reviews, required status checks, linear history, no force-push to main, signed commits), CODEOWNERS to route reviews, and merge queues (which test the PR against the future main to avoid “green PR, broken main”) turn your branching strategy into enforced policy. These settings are themselves configurable as code (IaC, e.g. the Terraform GitHub provider).

  • Git stores immutable snapshots as content-addressed objects; branches and tags are movable pointers. Commits are never edited, only replaced.
  • Merge preserves history; rebase rewrites it. Rebase only unshared branches, push with --force-with-lease.
  • Trunk-based development with feature flags and strong CI correlates with high delivery performance; GitFlow suits versioned products with multiple supported releases.
  • Monorepos need affected-only builds, ownership rules, and scale features to pay off.
  • Local hooks are convenience; enforcement belongs in CI and branch protection.
  • Sign commits (SSH or Sigstore) to attest authorship; the reflog and revert handle most mistakes, but leaked secrets require rotation, not history surgery.
  1. Hands-on. In a scratch repo, make three commits, then use git cat-file -p to walk from HEAD to a blob, writing down each hash. Change one file and show which objects are new.
  2. Hands-on. Create a branch with 4 messy commits and use git rebase -i to squash them to 2 well-formed commits. Then deliberately reset --hard to lose them and recover via the reflog.
  3. Conceptual. Your team of 40 deploys a SaaS API 10 times a day. Argue for or against GitFlow.
  4. Hands-on. Plant a bug 200 commits ago in a test repository and use git bisect run to find it. Count steps.
  5. Design. Write the branch-protection settings and CODEOWNERS rules for a monorepo with services/payments (needs security review) and docs/.
Solution notes (3)

Against: GitFlow’s develop and release branches delay integration and add merge overhead; with 10 deploys a day you effectively release continuously, so a release/* branch has no meaning. Prefer trunk-based development or GitHub Flow with flags. For: only if you must support several released versions in parallel (then use release branches off trunk instead of full GitFlow).

  • Scott Chacon and Ben Straub, Pro Git (2nd ed., free online), especially chapters on internals and branching.
  • Paul Hammant, trunkbaseddevelopment.com.
  • Vincent Driessen, “A successful Git branching model” (2010) and his later retrospective note.
  • Conventional Commits specification (v1.0.0).
  • Nicole Forsgren, Jez Humble, Gene Kim, Accelerate (2018), on trunk-based development and performance.