Continuous integration with Git

Continuous integration with Git #

What continuous integration is for #

Continuous integration is not “we have a build server”. A build server is a machine. CI is a promise, and the promise has two halves:

  1. the mainline is always known-good, so anybody can branch from it at any moment without inheriting somebody else’s mess;
  2. the feedback arrives while the author still remembers the change.

The second half is the one people underestimate. A test failure that reaches you in ninety seconds is a small annoyance. The same failure reaching you tomorrow morning is an archaeological dig, because you have already started something else and your head is empty of the context that would have made the bug obvious.

This is also why continuous integration and trunk-based development are the same idea seen from two angles. “Integrate small changes into the mainline constantly” and “keep the mainline green” are two halves of one sentence: you can only integrate constantly if the mainline is trustworthy, and the mainline only stays trustworthy if everyone integrates small changes. Long-lived branches are how teams get big scary merges; CI is how they stop needing them. We discussed the branching side of this argument in A little structure please.

What the CI system actually receives #

This is a Git course, so let us look at the mechanism rather than at a vendor’s dashboard.

When you git push, the server does two things. It updates a ref — and then it tells its subscribers, over HTTP, that a ref moved. That notification is the webhook, and conceptually it carries very little:

ref:    refs/heads/my-feature
before: 9c4f1b0e1a1c0f8b6d5a34e2b7c8d9e0f1a2b3c4
after:  3f2e1d0c9b8a77665544332211ffeeddccbbaa99
repo:   you/your-project
pusher: you@example.com

That is the same <oldrev> <newrev> <refname> triple that a pre-receive or post-receive hook reads on standard input — we will write one by hand in the next chapter. A hosted CI system is a post-receive hook with a nice web page attached, and every clever thing it does is built on those three values plus a clone.

The runner then clones your repository, checks out something, and runs your commands. Two of those steps deserve a hard look, because both hide traps.

Shallow clones, and what they break #

Cloning ten years of history to run a five-second test is wasteful, so CI systems clone shallow by default. In GitHub Actions this is actions/checkout with fetch-depth: 1 — one commit, no history. GitLab calls it GIT_DEPTH.

It is a real speedup, and it breaks four things:

  • git describe --tags — there are no tags and no history, so version stamping fails or lies.
  • git log archaeology, git blame, git bisect — there is nothing to walk.
  • “what changed since the base branch” — the base branch is not in the clone at all.
  • Any tool that computes a version or a changelog from history: semantic-release, git-cliff, and friends.

So: fetch-depth: 0 on the jobs that need history, fetch-depth: 1 on the jobs that do not. The failure mode is confusing enough to be worth a warning.

⚠️ A shallow clone can make a correct command produce a wrong answer rather than an error. git describe --tags --always in a depth-1 clone happily prints the abbreviated SHA and exits zero, so your artifact gets stamped 3f2e1d0 instead of v1.4.2 and nobody notices until an incident.

Partial clone is the more surgical modern option — git clone --filter=blob:none fetches all the commits and trees but no file contents until something asks for them. You get real history and a small download. Support in CI runners is uneven; it is worth trying when a full clone is the slowest part of your build.

Which commit is CI even testing? #

Here is the single most confusing thing about CI, and almost no tutorial explains it.

When you open a pull request, most systems do not test your branch. They test a merge of your branch into the target branch — a commit that exists in no repository you own.

GitHub materialises this as a pair of refs on the server side, and you can see them with plain Git. This is the real output of a real command against the Git project’s own repository:

$ git ls-remote https://github.com/git/git 'refs/pull/100/*'
d604669e32e847c2ba5010c89895dd707ba45f55	refs/pull/100/head
55ab0c9399879683b4cc6e1baea5dc41484ca52f	refs/pull/100/merge
  • refs/pull/100/head is the tip of the contributor’s branch, exactly as they pushed it.
  • refs/pull/100/merge is a merge commit GitHub created by merging that branch into the target branch as it stands right now. Nobody typed git merge. It appears in no one’s git log. It is recomputed whenever either side moves.

By default actions/checkout checks out the merge ref on a pull_request event. GitLab does the same thing under refs/merge-requests/<n>/merge (with the branch tip at refs/merge-requests/<n>/head), and the pipeline that tests it is called a merged results pipeline.

Two consequences follow, and both explain things you have probably lived through.

“It passed CI and then broke main.” Usually it did not. The merge ref was computed against main as it was an hour ago. Between then and your merge button, three other pull requests landed. The commit CI blessed and the commit that ended up on main are different commits, and nobody ever tested the second one.

“The diff CI shows me is not my diff.” If you test the merge ref, HEAD is a merge commit whose first parent is main, so HEAD~1 is somebody else’s commit. Any script that reasons about “the last commit” is now quietly wrong.

Merge queues are the fix. Instead of merging when you click, the platform queues your pull request, builds a temporary branch containing main plus the changes ahead of you in the queue plus yours, and tests that. Only if it is green does the batch land. GitHub calls it the merge queue and fires a distinct merge_group event that your workflow must listen for; GitLab calls it merge trains. If your team is big enough to have felt the race, you want one.

Checking out a pull request locally #

Those refs are fetchable, which is the most useful trick in this chapter for reviewers:

git fetch origin pull/100/head:pr-100
git switch pr-100

On GitLab:

git fetch origin merge-requests/100/head:mr-100
git switch mr-100

You now have the contributor’s actual commits as a local branch, and you can build them, run them, git log them and git range-diff them against the previous round of review. This works on any pull request in any public repository, including ones you cannot push to.

ℹ️ git fetch origin pull/100/head:pr-100 is just the refspec syntax from Working with remote repositories: source ref on the left, local destination on the right. Nothing special is happening — the forge simply publishes extra refs outside refs/heads/, which is why git clone does not bring them along by default.

Computing the changed file set, correctly #

Half of monorepo CI is the question “which files changed in this pull request?”, and the naive answer is wrong. Watch. A branch with two commits, each touching a different file:

$ git diff --name-only HEAD~1..HEAD
web.py
$ git diff --name-only $(git merge-base origin/main HEAD)..HEAD
api.py
web.py

HEAD~1 means “the previous commit”, which is your second-to-last change, not the point where your work started. Any change older than your last commit is invisible to it — and on a merge ref, HEAD~1 is not even yours.

The right question is “what changed since this branch left the mainline?”, which is exactly the merge base:

git diff --name-only $(git merge-base origin/main HEAD)..HEAD

Since Git 2.30 there is a shorthand that computes the merge base for you, and it is the one to memorise:

git diff --name-only --merge-base origin/main HEAD

git diff --name-only origin/main...HEAD — three dots — does the same thing, and is the form you will see in older scripts.

⚠️ All three require origin/main to actually be in the clone. A shallow CI checkout usually fetches only your branch, so the command dies with fatal: ambiguous argument 'origin/main': unknown revision or path not in the working tree. — a message that sends people hunting for a typo when the real problem is the clone depth. This is the most common way the shallow-clone trap bites.

Path filters and monorepo CI #

Once you can compute the changed set, you can skip work: do not run the iOS build when only the documentation changed. Every CI system offers this declaratively (on: push: paths: in GitHub Actions, rules: changes: in GitLab), and for simple repositories that is enough.

There is a correctness hazard, and it is a nasty one. Path filters express “these files changed”, but what you actually need is “these things could be affected”. Change a shared library that forty services import, and a naive filter runs the library’s own tests and nothing else. Everything is green. Everything is broken.

Two honest ways out:

  • Maintain the dependency mapping by hand: “if libs/auth/** changed, also run the services that depend on it.” Simple, works, and rots quietly as the dependency graph changes.
  • Let a build tool derive it. Bazel, Turborepo, Nx and Pants build a graph of targets, hash each target’s inputs including the hashes of its dependencies, and rebuild or retest exactly the targets whose hash changed. That is not a heuristic, it is a correct answer.

And note what that hashing is: content addressing, applied to build artifacts instead of to blobs. The idea is Git’s, and we look at it more closely in Things inspired by Git.

Caching #

The other big speedup. Restore node_modules, ~/.cargo, ~/.m2, .venv from the previous run instead of downloading the internet again.

Key the cache on a hash of the lockfile, never on the branch name. package-lock.json, poetry.lock, Cargo.lock, go.sum — that is precisely what lockfiles are for: they are a content hash of your dependency set, so if the lockfile is unchanged the cache is valid, and if it changed the cache should miss. A cache keyed on a branch name will happily serve you the wrong dependencies for weeks.

And do not cache anything you would not be comfortable finding in a colleague’s build. A cache is mutable state shared between runs of untrusted code; treat it as such.

Running tests #

The build itself, then the tests, in roughly the order of how fast they fail.

  • Build / compile. If it does not compile, nothing else matters. Fail here first.
  • Unit tests. Fast, hermetic, no network. These should run in seconds and should also run on the developer’s laptop before the push.
  • Integration tests. Real database, real queue, real HTTP. Slower, flakier, and the only tests that catch the mistakes that matter. Run them, but run them after the unit tests.
  • End-to-end tests. Valuable and expensive. Keep the set small and deliberate.

Two opinions, offered as opinions.

Order jobs so that the cheapest check that could fail runs first: a thirty-second lint failure is much kinder than a forty-minute test suite that fails on a missing semicolon.

And treat a flaky test as a broken test. A suite that fails one time in five teaches everyone to click “re-run”, which is the same as having no suite at all — and it destroys git bisect, which we are about to rely on.

Static analysis #

Everything in this section is a check that reads your code without running it. Grouped, with a recommendation attached.

Linters and formatters. Run them, and — strong opinion — make formatting automatic and non-negotiable. Adopt gofmt, black, ruff format, prettier, rustfmt, whichever is idiomatic, accept its defaults, and never discuss whitespace in a code review again. A human reviewing indentation is a human not reviewing your logic. The pre-commit framework is the standard way to run these before the commit is even made; see Making the command line yours for the hook mechanics.

Type checkers. mypy, pyright, tsc --noEmit. If your language has an optional type checker, running it in CI is the cheapest bug-finding you will ever buy.

Static analysis and SAST. golangci-lint, clippy, Semgrep, CodeQL. These look for bug patterns and security anti-patterns rather than style. Start with the default rule set; a security tool that cries wolf gets ignored, and an ignored tool is worse than no tool.

Dependency and vulnerability scanning. pip-audit, cargo audit, npm audit, osv-scanner, plus Dependabot or Renovate to open the upgrade pull requests for you. Renovate is the more configurable of the two; Dependabot is already switched on where you are.

Secret scanning. gitleaks or your forge’s built-in scanner. This one is genuinely important, because of the warning in GitOps: a secret that reaches the server has to be rotated, not deleted. Scanning in a pre-commit hook stops it before it exists; scanning in CI catches what got around the hook. Do both.

Licence checks. If you ship software commercially, somebody eventually asks which licences are in your dependency tree. A machine can answer that; make it.

Commit-level checks. The specifically Git-flavoured ones, and they are cheap: commit message conventions (commitlint), DCO sign-off (git commit -s), “no merge commits on this branch”, “no file larger than a megabyte” — before it becomes a permanent part of history — and “no fixup! commits left in the series”.

ℹ️ Notice how many of these belong in both places: a pre-commit hook for the fast feedback, and CI for the guarantee. Hooks are advisory — they live in .git/hooks, they are not cloned, and any colleague can --no-verify past them. CI is where the rule is actually enforced. Hooks are courtesy; CI is contract.

git bisect run, or why a green mainline pays for itself #

Some morning a test fails and nobody knows which of last week’s forty commits did it. Git can find it for you, automatically, in about six steps:

git bisect start HEAD HEAD~40      # HEAD is bad, HEAD~40 was good
git bisect run ./test.sh

Git checks out the midpoint, runs your script, reads its exit code — zero is good, non-zero is bad — and halves the range again, until:

running './test.sh'
8228d7412652f77476b8c08ea3a3833035955d86 is the first bad commit
commit 8228d7412652f77476b8c08ea3a3833035955d86
Author: Ori Pekelman <ori+git-training@pekelman.com>

    commit 4

 app.py | 2 ++
 1 file changed, 2 insertions(+)
bisect found first bad commit

Then git bisect reset to come home. (Your hashes will differ, obviously.)

The script can be anything that exits zero or non-zero: pytest -x tests/test_login.py, make check, a two-line grep. Exit code 125 means “cannot test this commit, skip it”.

Now the argument. Bisect works by assuming that every commit either passes or fails for a reason. If your mainline is a swamp of broken commits, bisect lands on one that does not build, you are forced to skip it, and the search degrades into guesswork. A green mainline is what makes automated bisection possible — which is to say that keeping CI green is not box-ticking, it is buying yourself a debugging superpower for later.

Required checks, branch protection, and the race they do not fix #

Every forge lets you mark checks as required: main cannot be merged into unless the checks pass. Turn this on. Combined with “require a review” and “require the branch to be up to date”, it is 90% of what people call process.

But hold on to the thing we learned above. Two pull requests, each green against main, each individually reviewed. A renames a function; B adds a caller of the old name. Both merge. main is broken, and no test ever ran against the combination. “Require branches to be up to date before merging” fixes this by forcing a rebase-and-rerun on the second one — at the cost of serialising your team, since every merge invalidates every other open pull request.

The merge queue is the grown-up version: it batches, builds main + queued changes, tests the batch, and lands it. Same guarantee, without the manual rebase treadmill.

The vendors, briefly and evenly #

  • GitHub Actions. Ubiquitous, YAML, an enormous marketplace of reusable actions, generous free tier for public repositories. Debugging is mediocre and the expression syntax is a language nobody chose.
  • GitLab CI. One .gitlab-ci.yml, a coherent model of stages and artifacts, excellent self-hosted story. The YAML gets baroque at scale.
  • Forgejo Actions. Actions-compatible workflows on a small, self-hostable, genuinely free forge. Good if you want to leave the big platforms without rewriting everything.
  • CircleCI. Fast, mature, good caching and parallelism primitives.
  • Buildkite. You host the runners, they host the coordination. The favourite of teams with large, weird builds.
  • Jenkins. Still everywhere, and honestly: people leave because the pipeline lives in a server’s mutable state and a hundred plugins rather than in the repository, which makes it hard to reproduce and hard to review. If your Jenkins config is in Git as a Jenkinsfile, most of that objection goes away.
  • Woodpecker and Drone. Small, container-native, pleasant, self-hosted.

⚠️ Pin third-party actions to a commit SHA, not to a tag: uses: some-org/some-action@a1b2c3d4…, not @v3. A tag is a ref — a movable pointer to a commit — and the person who owns it can move it whenever they like, including to code that exfiltrates your secrets. This is not paranoia; it is how several real supply-chain attacks worked. A SHA is content-addressed and cannot be repointed. GitHub’s own documentation pins actions this way in its OIDC examples. Everything we learned about branches-versus-hashes in Part 1 turns out to be a security property.

And one more option, which is the advice I actually give: put your checks in a Makefile or a just file — make lint, make test — and let CI merely invoke them. If CI can only be run by CI, you have a debugging problem: every experiment costs a push and a five-minute wait. If make test is the same thing locally and remotely, you can fix it on your laptop.

A complete workflow you can paste #

GitHub Actions, because that is what most readers have. Checkout with enough depth, a toolchain, a cache, lint, test, and one job that runs only when a particular directory changed.

# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:
  merge_group:          # required for the merge queue to see these checks

permissions:
  contents: read        # least privilege; add more only where a job needs it

concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      # Major versions current as of this writing. For third-party actions, pin a commit
      # SHA instead of a tag; for actions/* a major tag is a reasonable compromise.
      #
      # Fast-moving: Action versions change frequently. Check for updates.
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0            # we want history: describe, blame, merge-base

      - uses: actions/setup-node@v7
        with:
          node-version: '22'
          cache: npm                # keyed on package-lock.json for us

      - run: npm ci
      - run: make lint              # same target we run on our laptops
      - run: make test

  changed:
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request'
    outputs:
      docs: ${{ steps.filter.outputs.docs }}
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0

      - id: filter
        env:
          BASE: ${{ github.event.pull_request.base.ref }}
        run: |
          git fetch --quiet origin "$BASE"
          files=$(git diff --name-only --merge-base "origin/$BASE" HEAD)
          echo "changed files:"; echo "$files"
          if echo "$files" | grep -q '^docs/'; then
            echo "docs=true" >> "$GITHUB_OUTPUT"
          else
            echo "docs=false" >> "$GITHUB_OUTPUT"
          fi

  docs:
    needs: changed
    if: needs.changed.outputs.docs == 'true'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: make docs

ℹ️ The changed job only runs on pull requests, because on a push the merge base of origin/main and HEAD is HEAD and the diff comes back empty. For a push, the equivalent range is ${{ github.event.before }}..${{ github.sha }} — the two SHAs from the webhook we started the chapter with.

The same shapes in GitLab, so you can see that nothing here is GitHub-specific:

# .gitlab-ci.yml
stages: [test]

default:
  image: node:22

variables:
  GIT_DEPTH: "0"          # full history, same reason as fetch-depth: 0

cache:
  key:
    files:
      - package-lock.json # cache keyed on the lockfile's content
  paths:
    - node_modules/

lint:
  stage: test
  script:
    - npm ci
    - make lint

test:
  stage: test
  script:
    - npm ci
    - make test

docs:
  stage: test
  rules:
    - changes:
        - docs/**/*      # GitLab computes the changed set for us
  script:
    - make docs

Two files, two dialects, one idea: fetch the right commit, restore a cache keyed on a lockfile, run the same targets you run at home.

Summary git ls-remote git diff --merge-base git bisect run #

  • CI exists to keep the mainline known-good and to give feedback while the change is still fresh. It is trunk-based development seen from the tooling side.
  • A CI trigger is a webhook carrying <before>, <after> and a ref — the same triple a post-receive hook reads — plus a clone.
  • Shallow clones (fetch-depth: 1, GIT_DEPTH) break git describe, blame, bisect, changelog generation and merge-base computation. Use fetch-depth: 0 where history matters.
  • On a pull request, CI usually tests a merge commit that exists in no repository: refs/pull/<n>/merge on GitHub, refs/merge-requests/<n>/merge on GitLab. …/head is the branch tip. git ls-remote shows you both.
  • That is why “it passed CI then broke main” happens, and why merge queues (GitHub’s merge_group) and merge trains (GitLab) exist.
  • git fetch origin pull/<n>/head:pr-<n> checks out any pull request locally.
  • Compute changed files with git diff --name-only --merge-base origin/main HEAD, never with HEAD~1.
  • Path filters skip work but can miss dependents; content-hash build graphs (Bazel, Nx, Turborepo) are the rigorous answer.
  • Key caches on lockfile hashes.
  • Run build, unit tests, integration tests, formatters, linters, type checkers, SAST, dependency and secret scanning, licence and commit-level checks — many of them in a pre-commit hook and in CI.
  • git bisect run ./test.sh finds the offending commit automatically — and only works well if the mainline is mostly green.
  • Pin third-party actions to a commit SHA, because tags move.
  • Put the real commands in make/just targets so CI is not the only place they can run.