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.
The data model
Section titled “The data model”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:
git init demo && cd demoecho hello > a.txt && git add a.txt && git commit -m "first"git cat-file -t HEAD # commitgit cat-file -p HEAD # shows tree, author, messagegit cat-file -p 'HEAD^{tree}' # lists blobsgit rev-parse HEADgit count-objects -vHA 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.
cat .git/HEAD # ref: refs/heads/maincat .git/refs/heads/main # the commit hashgit branch feature # writes a new ref fileCommitting 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).
Index, working tree, and the three trees
Section titled “Index, working tree, and the three trees”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).
Merge versus rebase
Section titled “Merge versus rebase”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.
git switch featuregit fetch origingit rebase origin/main # replay feature onto latest maingit rebase -i origin/main # interactive: reorder, squash, fixup, reword, dropgit push --force-with-lease # safe force push after rebasing a branch only you use
git switch maingit merge --no-ff feature # always create a merge commitgit merge --squash feature && git commitThe 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.
Conflicts
Section titled “Conflicts”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.
<<<<<<< HEADtimeout = 30=======timeout = 60>>>>>>> featureResolve, 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.
Branching strategies
Section titled “Branching strategies”Trunk-based development (TBD)
Section titled “Trunk-based development (TBD)”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.
GitHub Flow
Section titled “GitHub Flow”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.
GitFlow
Section titled “GitFlow”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.
Commit hygiene
Section titled “Commit hygiene”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 versus polyrepo
Section titled “Monorepo versus polyrepo”| 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 subjectset -euo pipefailsubject=$(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; }git config core.hooksPath .githookschmod +x .githooks/commit-msgLocal hooks are bypassable (--no-verify), so treat them as developer convenience and enforce the same checks in CI and branch protection.
Signed commits and tags
Section titled “Signed commits and tags”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.
git config --global gpg.format sshgit config --global user.signingkey ~/.ssh/id_ed25519.pubgit config --global commit.gpgsign truegit config --global tag.gpgsign true
# verify locally: map allowed signersecho "you@example.com $(cat ~/.ssh/id_ed25519.pub)" > ~/.config/git/allowed_signersgit config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signersgit log --show-signature -1GPG remains supported; Sigstore gitsign gives keyless signing using OIDC identities (see DevSecOps). Combine signing with branch protection (“require signed commits”) for supply-chain assurance.
Useful power tools
Section titled “Useful power tools”git log --oneline --graph --decorate --allgit log -S'needle' # pickaxe: commits that added/removed a stringgit log -L :funcname:file.py # history of a functiongit blame -w -C file.py # ignore whitespace, detect moved linesgit bisect start; git bisect bad; git bisect good v1.2.0git bisect run ./test.sh # automatic binary search for the breaking commitgit worktree add ../hotfix main # second checkout without cloninggit stash push -m "wip" -ugit diff --stat main...HEAD # three-dot: changes since merge basegit range-diff old..new # compare two versions of a rebased seriesgit bisect run is a superpower: with commits it finds the culprit in about steps, so 1000 commits take 10 test runs.
Recovering from mistakes
Section titled “Recovering from mistakes”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 |
git reflog# 3f2a1b9 HEAD@{0}: reset: moving to HEAD~3# a91c4de HEAD@{1}: commit: add retry logic <- what you wantgit reset --hard a91c4deRepository policy as pipeline input
Section titled “Repository policy as pipeline input”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).
Key takeaways
Section titled “Key takeaways”- 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
reverthandle most mistakes, but leaked secrets require rotation, not history surgery.
Exercises
Section titled “Exercises”- Hands-on. In a scratch repo, make three commits, then use
git cat-file -pto walk fromHEADto a blob, writing down each hash. Change one file and show which objects are new. - Hands-on. Create a branch with 4 messy commits and use
git rebase -ito squash them to 2 well-formed commits. Then deliberatelyreset --hardto lose them and recover via the reflog. - Conceptual. Your team of 40 deploys a SaaS API 10 times a day. Argue for or against GitFlow.
- Hands-on. Plant a bug 200 commits ago in a test repository and use
git bisect runto find it. Count steps. - Design. Write the branch-protection settings and CODEOWNERS rules for a monorepo with
services/payments(needs security review) anddocs/.
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).
Further reading
Section titled “Further reading”- 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.