Branching Ecosystems

Branching Ecosystems in DevOps Tools: --- In the drawing office of a county highway authority there is a plan chest, and in its top drawer lies the master plan…


The Analogy: The Survey Office's Master Plan and Its Tracings

In the drawing office of a county highway authority there is a plan chest, and in its top drawer lies the master plan of a road: one large linen sheet, inked, showing every kerb line, gully and chainage marker along eleven miles of carriageway. It is the only sheet that counts. When a contractor is sent out to widen a junction, nobody hands them the master. A draughtsman lays tracing paper over it, copies the corner tick marks that register the tracing against the master, traces the section that concerns the job, and sends the tracing out. The contractor marks proposed changes on it in pencil. The master stays in the drawer, untouched, and three other contractors can be out with three other tracings of three other sections at the same time.

When a tracing comes back, the checker lays it over the master and lines up the tick marks. If nothing on the master has moved since the tracing was taken, so those marks still describe the sheet exactly as it is, there is nothing to reconcile: the draughtsman inks the pencil lines straight onto the master and the job is finished. No new sheet, no reconciliation note; the master simply now includes the work as though it had always been there. That is a fast-forward, where the branch label slides along to a commit already sitting ahead of it and no merge commit exists because none was needed.

The interesting case is two tracings that both alter the same chainage. The checker lays down the first, then the second, and sees pencil crossing pencil: one contractor has moved the kerb out by a metre, the other has put a bus lay-by exactly there. The office does not average them, and it does not quietly prefer the sheet that came back later. A clerk brings both contractors in, they agree one set of lines, and the reconciled sheet is inked with an entry in the register recording that it derives from both tracings, so that anyone can follow either lineage backwards. That register entry is the merge commit, and the two lineages it names are its two parents. A merge commit is the only kind of commit in Git with more than one parent, and it exists precisely because there was something to decide.

The failure mode is the tracing taken in March and returned in September. The tick marks still register, so the checker can still lay it down, but the master has been inked over a dozen times in between, and a reconciliation that would have taken five minutes in March now takes a fortnight and produces a road nobody designed. Note also what the checker never does: because each tracing is compared only against the tick-marked state it came from, a tracing adding a lay-by three miles from anything else needs no discussion at all, however much of the rest of the plan changed while it was out. The cost of a merge is not the age of the branch; it is the overlap between what moved on the branch and what moved underneath it.


Syntax or Core Structure

Four commands cover the whole cycle: create a branch, switch to it, commit on it, merge it back. Start from a repository holding one file, so that every number printed below is reproducible on your machine.

git init -q -b main theme-demo
cd theme-demo
printf 'light\n' > theme.txt
git add theme.txt
git commit -qm 'feat: add theme'

git branch feature/dark-mode
git branch

Output:

  feature/dark-mode
* main

git branch created a second label pointing at the commit you are standing on and did not move you; the asterisk marks where HEAD is. Both labels name the same commit and the working tree did not change, which is why creating a branch costs one file holding one hash rather than a copy of your project.

Now do work on the branch and bring it home.

git switch -q feature/dark-mode
printf 'dark\n' > theme.txt
git commit -qam 'feat: dark theme'

git switch -q main
git merge-base --is-ancestor main feature/dark-mode && echo 'main is behind'
git merge feature/dark-mode | tail -n +2

Output:

main is behind
Fast-forward
 theme.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

The tail -n +2 is not decoration: git merge opens with Updating followed by two abbreviated hashes, and hashes are the sort of value that makes a tutorial rot, so that line is dropped on purpose. git merge-base --is-ancestor A B asks the question the merge is about to answer for itself: it exits zero when A is reachable from B, which is the precise condition for a fast-forward.

The state afterwards is worth reading rather than assuming.

git log --format='%s' HEAD
git rev-list --count HEAD
git cat-file -p HEAD | grep -c '^parent '

Output:

feat: dark theme
feat: add theme
2
1

Two commits, and the tip has one parent: the merge produced no commit of its own. main and feature/dark-mode are two labels on one object, so deleting the branch now would lose nothing -- a label is not where the work lives.

Let main move too, and the shape of the answer changes completely.

git init -q -b main two-sided
cd two-sided
printf 'light\n' > theme.txt
printf 'v1\n' > version.txt
git add .
git commit -qm 'chore: seed'

git switch -qc feature/dark-mode
printf 'dark\n' > theme.txt
git commit -qam 'feat: dark theme'

git switch -q main
printf 'v2\n' > version.txt
git commit -qam 'chore: bump version'

git merge-base --is-ancestor main feature/dark-mode || echo 'main has moved too'
git merge --no-edit feature/dark-mode

Output:

main has moved too
Merge made by the 'ort' strategy.
 theme.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

git switch -qc is create-and-switch in one step, the modern spelling of git checkout -b. The merge could not fast-forward this time, because main carries a commit the branch has never seen, so Git built a new commit instead. Notice that the summary mentions only theme.txt: the diff shown for a merge commit is against its first parent, so the version.txt change already on main does not appear as part of the merge.

git log --first-parent --format='%s'
git rev-list --count HEAD
git cat-file -p HEAD | grep -c '^parent '

Output:

Merge branch 'feature/dark-mode'
chore: bump version
chore: seed
4
2

Four commits exist and the tip has two parents, yet the first-parent walk lists three. --first-parent follows the branch you were standing on at each merge and steps over what came in from the side, which is the reading that matches how a release manager thinks about main.


Technical Depth: What a Branch Actually Is

A branch is one small file containing one hash

The word "branch" suggests something substantial. It is not. Look at the thing directly.

git init -q -b main refs-demo
cd refs-demo
printf 'x\n' > x.txt
git add x.txt
git commit -qm 'chore: seed'

wc -c .git/refs/heads/main
cat .git/HEAD
git rev-parse --symbolic-full-name HEAD

Output:

41 .git/refs/heads/main
ref: refs/heads/main
refs/heads/main

Forty-one bytes: forty hexadecimal characters and a newline. That is the entire branch. HEAD is one level of indirection above it -- a file whose contents are the text ref: refs/heads/main, which is what "you are on a branch" means. Committing rewrites those forty-one bytes; switching branches rewrites .git/HEAD. Once a repository has many refs Git may pack them into .git/packed-refs rather than one file each, so treat the loose file as an illustration and use git rev-parse to read the value.

The four kinds of ref you will actually meet behave quite differently.

Ref kindWhere it livesWhat it namesWhat moves it
Local branchrefs/heads/NAMEa commityour commits, merges and resets
Remote-trackingrefs/remotes/REMOTE/NAMEa commitgit fetch and git push only, never a local commit
Lightweight tagrefs/tags/NAMEa commitnothing: you delete it and make a new one
HEAD.git/HEADa branch by name, or a commit when detachedgit switch and git checkout

The one that surprises people is the remote-tracking ref. origin/main is not the branch on the server; it is your local note of where the server's branch was the last time you spoke to it. Nothing local moves it except fetching and pushing, which is why git status can cheerfully report you up to date with a server you have not contacted in a week.

The merge base decides everything

A merge is not a comparison of two branch tips. It is a comparison of three things: the two tips and the newest commit reachable from both of them, called the merge base. git merge-base --all A B prints it, and prints more than one line only in the unusual case of a criss-crossed history with several equally-good bases, which the default strategy handles by merging the bases together first and using the result. Everything else about a merge follows from where that base sits relative to the two tips.

Where the base sitsWhat Git doesNew commit?Working tree touched
The branch tip is already the baseprints Already up to date.nono
The base is the target's own tipfast-forward: slides the labelnoyes
Both tips moved since the basethree-way mergeyes, with two parentsyes
There is no base at allfatal: refusing to merge unrelated historiesnono

Two of those messages are worth recognising on sight. Already up to date. means the branch holds nothing you do not have, not that the merge failed. The unrelated histories refusal almost always means you initialised a repository locally and then added a remote that already had its own initial commit; the flag that overrides it should make you stop and check you are merging the repository you think you are.

A conflict is a state, not an error message

When both sides changed the same region, Git stops and leaves the repository in a state you can inspect.

git init -q -b main conflict-demo
cd conflict-demo
printf 'const theme = "light";\n' > theme.js
git add theme.js
git commit -qm 'chore: seed'

git switch -qc feature/dark-mode
printf 'const theme = "dark";\n' > theme.js
git commit -qam 'feat: dark theme'

git switch -q main
printf 'const theme = "high-contrast";\n' > theme.js
git commit -qam 'feat: high contrast'

git merge --no-edit feature/dark-mode
echo "exit=$?"
git status --short
git diff --name-only --diff-filter=U

Output:

Auto-merging theme.js
CONFLICT (content): Merge conflict in theme.js
Automatic merge failed; fix conflicts and then commit the result.
exit=1
UU theme.js
theme.js

UU in the two status columns means unmerged on both sides, and --diff-filter=U is how a script asks for exactly the conflicted paths without parsing prose. What makes this state recoverable rather than merely broken is that the index is now holding three versions of the file at once, under numbered stages.

git ls-files --unmerged | awk '{print $3}'
git show :1:theme.js
git show :2:theme.js
git show :3:theme.js

Output:

1
2
3
const theme = "light";
const theme = "high-contrast";
const theme = "dark";
StageNameWhich version it holds
1basethe merge base, the ancestor both sides started from
2oursthe tip of the branch you are standing on
3theirsthe tip of the branch being merged in

Those three stages are why git checkout --ours theme.js and --theirs work, why git merge --abort can put everything back exactly as it was, and why the markers in the file are a convenience rather than the source of truth. The markers are generated from stages 2 and 3; the stages are the real record. Deleting the markers by hand and saving is not resolution -- resolution is git add, which collapses the three stages back to one and is the only thing that tells Git you have decided.


Real World Example: A Preflight Check That Cries Wolf

Teams that merge often want to know what a merge involves before starting one: how far apart the branches have drifted, whether it will be a fast-forward, and which files are likely to need a human. Here is a script that answers those questions without touching the working tree or creating a commit, so it is safe inside a pull-request check.

#!/usr/bin/env bash
# merge-preflight.sh <target> <topic> -- describe the merge of <topic> into
# <target> without touching the working tree or creating any commit.
set -u

target=$1
topic=$2

base=$(git merge-base "$target" "$topic") || { echo "preflight: no common ancestor"; exit 2; }

ahead=$(git rev-list --count "$target".."$topic")
behind=$(git rev-list --count "$topic".."$target")

echo "target=$target topic=$topic"
echo "ahead=$ahead behind=$behind"

if git merge-base --is-ancestor "$target" "$topic"; then
  echo "kind=fast-forward"
else
  echo "kind=three-way"
fi

overlap=$(comm -12 <(git diff --name-only "$base" "$target" | sort) <(git diff --name-only "$base" "$topic" | sort))

n=$(printf '%s' "$overlap" | grep -c . || true)
echo "overlap=$n"
printf '%s' "$overlap" | grep . | while IFS= read -r p; do echo "  both: $p"; done

if [ "$n" -gt 0 ]; then
  echo "preflight: both branches touched the files above"
  exit 1
fi
echo "preflight: no file was touched on both sides"
exit 0

Give it a repository where the two sides have genuinely diverged. Save the script one directory above the repository so that it does not appear as an untracked file inside it.

git init -q -b main checkout-app
cd checkout-app
mkdir -p src

cat > src/cart.js <<'JS'
export function addItem(cart, sku) {
  cart.push(sku);
  return cart;
}

export function total(cart, prices) {
  return cart.reduce((s, k) => s + prices[k], 0);
}
JS

cat > src/pay.js <<'JS'
export function charge(cents) {
  return cents;
}
JS

printf '# Checkout\n' > README.md
git add .
git commit -qm 'chore: seed checkout'

git switch -qc feature/checkout
cat > src/cart.js <<'JS'
export function addItem(cart, sku) {
  if (!sku) throw new Error("sku required");
  cart.push(sku);
  return cart;
}

export function total(cart, prices) {
  return cart.reduce((s, k) => s + prices[k], 0);
}
JS
git commit -qam 'fix: reject an empty sku'
printf 'export const vat = (cents) => Math.round(cents * 0.2);\n' > src/tax.js
git add src/tax.js
git commit -qm 'feat: add vat helper'

git switch -q main
cat > src/cart.js <<'JS'
export function addItem(cart, sku) {
  cart.push(sku);
  return cart;
}

export function total(cart, prices) {
  if (!prices) return 0;
  return cart.reduce((s, k) => s + prices[k], 0);
}
JS
git commit -qam 'fix: guard a missing price table'

bash ../merge-preflight.sh main feature/checkout
echo "exit=$?"

Output:

target=main topic=feature/checkout
ahead=2 behind=1
kind=three-way
overlap=1
  both: src/cart.js
preflight: both branches touched the files above
exit=1

Two commits to bring in, one commit the branch has not seen, no fast-forward available, and one file that both sides edited. Now ask Git the same question properly and then actually perform the merge.

git merge-tree --write-tree main feature/checkout >/dev/null 2>&1
echo "conflicts=$?"
git merge --no-edit feature/checkout
echo "exit=$?"

Output:

conflicts=0
Auto-merging src/cart.js
Merge made by the 'ort' strategy.
 src/cart.js | 1 +
 src/tax.js  | 1 +
 2 files changed, 2 insertions(+)
 create mode 100644 src/tax.js
exit=0

The merge was clean. Both guards survived: one branch added a check at the top of addItem, the other at the top of total, and Git applied both without asking anybody anything.

The parts of this script that earn their place are the range syntax and the ancestry test. git rev-list --count A..B counts commits reachable from B but not from A, so ahead and behind are the same two-dot range with the ends swapped -- there is no separate "how far behind" command, only that symmetry. git merge-base --is-ancestor communicates purely through exit status, which is why it appears as an if condition. And because every question is asked of the object store rather than the checkout, nothing here can leave a repository half-merged; comm -12 is set intersection over two sorted name lists.

Read against the analogy, the script is the clerk who counts how many tracings are outstanding and which chainages they cover before anyone unrolls a sheet on the light table. behind rising steadily over days is the measurable version of "this tracing was taken in March", and it predicts the cost of the reconciliation far better than the diff size does.

Now the flaw, not a rough edge but the central idea being wrong. The script reports overlap, and overlap is neither necessary nor sufficient for a conflict. The run above proves the "not sufficient" half: it printed overlap=1 and exited 1, while git merge-tree printed conflicts=0 and the real merge sailed through. Two people editing different functions in the same file is the commonest shape of collaborative work, so this check fires almost every time and teaches its users to ignore it -- a warning nobody reads is worse than no warning. The fix is to ask the merge machinery instead: git merge-tree --write-tree TARGET TOPIC performs the whole merge in memory, exits 1 on conflicts, and with --name-only lists exactly the conflicted paths, touching nothing. Three further defects are worth naming. Run it again after the merge and it prints ahead=0 yet still claims kind=three-way, where git merge would say Already up to date. -- nothing would be merged at all. It splits the intersection on newlines, so a path containing a space or a newline is mangled, and git diff --name-only will happily produce such paths. And it ignores renames: a file renamed on one side and edited on the other has different names in the two lists, so it never appears in the intersection, though that is one of the cases most likely to need a human.


Common Mistakes

  1. Believing a branch is a copy of the project. It is forty-one bytes naming a commit. Nothing is duplicated, which is why creating one is instant and deleting one deletes no work. People who think branches are expensive end up doing feature work directly on main.
  1. Running git branch NAME and then committing, expecting the commit to land on NAME. git branch creates the label and leaves HEAD where it was, so the next commit goes to the branch you were already on. Use git switch -c NAME, or check git branch --show-current first.
  1. Reading origin/main as the server's current state. It is a local note of where the server was when you last fetched, so a build that "works against origin/main" may be working against a week-old snapshot. Fetch first, and read git status as a comparison against that note rather than against the server.
  1. Deleting the conflict markers, saving the file, and calling it resolved. The markers are generated from stages 2 and 3 of the index, and editing the file does not touch the stages. Until you git add the path, Git still considers it unmerged and will refuse to commit. Resolution is a staging operation that happens to involve editing.
  1. Staging a file that still contains markers. The opposite error, and worse, because Git will not stop you: once you git add a file with <<<<<<< in it, the conflict is resolved as far as Git is concerned and the markers go into the commit. Grep the staged content for markers before committing a merge.
  1. Judging the cost of a merge by the size of the diff. A ten-thousand-line branch touching files nobody else went near merges silently; a forty-line branch editing a file rewritten twice underneath it can cost a day. What predicts pain is how far behind the branch is, not how big it is.
  1. Using git checkout for everything. One verb switches branches, creates branches, restores single files from a commit, and discards uncommitted work in the tree. That last behaviour is silent, irreversible, and one typo away from the others. git switch and git restore exist because of the accidents it caused.
  1. Treating a conflicted merge as a disaster to escape by re-cloning. The repository holds strictly more information than it did before: base, yours and theirs are all in the index. git merge --abort returns you exactly to where you started, and git show :1:FILE shows what both sides were editing away from.
  1. Resolving with git checkout --ours FILE to make the conflict go away. That takes your side of the entire file, discarding every change the other branch made to it, including the parts that merged cleanly and were never in dispute. It is right only for genuinely unmergeable content such as a lockfile or a binary asset.

Best Practices

  • Branch from a freshly fetched target. git fetch then git switch -c feature/x origin/main starts you from what the server actually has, so the merge base is as new as possible and the reconciliation as small as possible.
  • Keep branches short-lived, and measure it. Print git rev-list --count BRANCH..main in your pull-request check. A branch whose count climbs day after day is accumulating a cost nobody can see in the diff.
  • Use git switch and git restore instead of git checkout. Two narrow verbs that cannot be mistaken for each other are worth more than one flexible one, especially in scripts and in instructions you hand to someone else.
  • Decide fast-forward policy per repository, not per merge. Set merge.ff deliberately: fast-forwards keep a linear history for trivial branches, while --no-ff guarantees every piece of work is a unit that --first-parent and git revert -m 1 can address whole. Doing both at random is what hurts.
  • Look at stage 1 before you resolve. git show :1:FILE tells you what the other side was changing away from, which is usually the context that makes the right resolution obvious. Resolving from the markers alone means guessing at intent.
  • Test the merge result, not the branches. Both sides passing their own tests says nothing about the combination: a clean textual merge can still be a semantic conflict, one side renaming a function while the other adds a call to the old name.
  • Predict merges with the merge machinery. git merge-tree --write-tree answers "would this conflict" exactly and touches nothing. Any prediction built from lists of file names is a heuristic that will both cry wolf and stay silent when it matters.
  • Delete merged branches, and let Git protect you. git branch -d NAME refuses when the work is not reachable from where you stand; treat the refusal as a question rather than an obstacle, and reach for -D only after checking. A short branch list is a readable one.

Practice Exercises

  1. Break the preflight, then fix it properly. Reproduce the false positive from the Real World Example, then rewrite the overlap check to call git merge-tree --write-tree --name-only TARGET TOPIC, using its exit status for the verdict and its path list for the report. Verify that the same repository now reports zero conflicts, then construct a case where both sides edit the same line and confirm the rewritten script reports it.
  1. Find a history with two merge bases. Starting from one commit, create two branches, commit on each, then merge each into the other so the histories criss-cross. Run git merge-base --all on the two tips and report how many lines it prints and why. Then explain what the default strategy does with that answer.
  1. Resolve a conflict entirely through the index. Create a conflict in a file, and without opening an editor, print all three stages with git show :1:, :2: and :3:. Write the resolution with a shell command, git add it, and prove the stages collapsed by showing that git ls-files --unmerged now prints nothing. Then repeat with git merge --abort instead, proving the repository is byte-identical to before.
  1. Compare the two history shapes. Build the same branch twice and integrate it once with a fast-forward and once with --no-ff. For each result report git rev-list --count HEAD, the number of parents on the tip commit, and the output of git log --first-parent --format='%s'. State which of the two lets you later revert the whole feature with a single command, and which one loses the information that the commits belonged together.