Lesson 5 of 28Git in a team
Commits Your Teammates Thank You For
Make atomic commits, stage them precisely, write messages that explain why, keep secrets out with hooks, and set up Git once so it stays out of your way.
A teammate opens your pull request and sees one commit called changes that touches 31 files. It renames a module, fixes a rounding bug, bumps a dependency and reformats two folders. They cannot tell which lines are the fix, so they skim and approve. Two weeks later the dependency bump breaks production, and the only way to revert it also reverts the bug fix. Nothing about that was hard to avoid. Commits are the smallest unit your team reviews, reverts, bisects and reads in blame, and how you shape them decides how easy all of that is. This lesson is about making commits that are easy to review, safe to undo and still useful to whoever reads them in two years.
One commit, one logical change
An atomic commit does one thing, completely. "One thing" is a logical change, not a file count: adding a column and the code that reads it is one change across four files. Renaming a function and fixing a bug in it are two changes, even in one file.
The test is simple. Could you describe it in one short sentence without "and"? Would the project still build and pass its tests if this were the last commit? If both answers are yes, it is atomic.
You already saw why in the bisect section of Git archaeology: a first bad commit of 20 lines points straight at the bug, and a 900-line one does not. Atomic commits pay off everywhere else too:
- Review. A reviewer can read a pure rename at speed and spend their attention on the five lines of real logic.
- Revert. You can undo the dependency bump without undoing the fix.
- Cherry-pick. A fix that needs to go to a release branch can be copied on its own.
- Blame. The line's last commit explains that line, not twelve unrelated things.
The most valuable split is refactor first, behaviour change second. Kent Beck's advice is "make the change easy, then make the easy change". If the fix needs a function extracted, extract it in one commit that changes no behaviour (tests stay green, nothing new), then make the fix in a small commit on top. A reviewer can confirm the first is a no-op and focus on the second.
At the end of a session, git status shows a dozen changed files. Do not git add . and hope.
Staging precisely
Atomic commits come from staging hunks, not files. git add -p (patch mode) walks through each changed hunk and asks what to do:
git add -p # go hunk by hunk through every changed file# y stage this hunk n skip it# s split it into smaller hunks# e edit the hunk by hand q quit, keeping what you stagedgit add -N new_file.py # "intent to add": lets -p see a brand new filegit diff --staged # exactly what will be committedgit commit -v # opens the editor with that diff shown below the messageNew, untracked files are invisible to git add -p until you run git add -N on them. Setting git config --global commit.verbose true makes every commit show its diff in the editor, so you reread what you are committing at the moment you describe it. That one setting catches a surprising number of stray debug lines.
Before you push, history is yours to tidy. git commit --amend fixes the last commit (add a forgotten file, fix the message). For older commits, git commit --fixup <sha> plus an interactive rebase folds a correction into the commit it belongs to; Rebase, Merge and Squash covers that workflow. Once the branch is pushed and someone is reviewing it, prefer adding commits over rewriting, which Pull requests that get reviewed fast explains.
orders.py, and while there you renamed a variable everywhere in the file and ran the formatter. What is the best set of commits?Messages that explain why
The diff already shows what changed. The message is for what the diff cannot show: why it changed, what you considered, and anything surprising. The shape is old and nearly universal:
Round cart totals only when displaying them
total() rounded to whole pounds, so 3 items at 2.50 came out as 8
instead of 7.50 and payment captured the wrong amount. Keep full
precision in total() and round in the template filter instead.
The invoice export already formats its own numbers, so it is not
affected. Tested with the 2.5 x 3 case from SHOP-482.
Fixes SHOP-482
Co-authored-by: Sam Lee <sam@example.com>- Subject: about 50 characters, 72 at most, because tools truncate it (
git log --oneline, GitHub's commit list, email subjects). Imperative mood: "Round totals", not "Rounded totals". It should complete "If applied, this commit will...". No full stop. - Blank line, then the body, wrapped at 72 characters so it reads well in a terminal. Explain the problem, the reason for this approach, and side effects. Skip the body for truly obvious changes like "Fix typo in README".
- Trailers at the end, as
Key: valuelines. Ticket references, andCo-authored-by:for pair or mob work, which GitHub shows as extra authors.git commit --trailer "Co-authored-by: Sam Lee <sam@example.com>"adds one for you.
On GitHub, a commit or PR description containing Fixes #123 (or Closes, Resolves) closes that issue when it is merged into the default branch. Jira and Linear have their own smart keywords; check what your team uses.
Bad messages are not just ugly. "fix", "wip", "address review comments" and "final" force the next person to reverse-engineer intent from the diff, which is exactly the archaeology this course's earlier lesson tried to make quick.
The block below is a small commit-message linter, the same kind of rules a commit-msg hook or a CI check enforces. Try your own messages on it.
Press Run (⌘ Enter) to see what happens.Using the lint function above, what does this print?
print("; ".join(lint("Removed old flag\nSee ticket SHOP-12")))Conventional Commits
Some teams require Conventional Commits (version 1.0.0 of the spec), a structured subject that machines can read:
feat(cart): add saved-for-later list
fix(api): return 404 instead of 500 for unknown order ids
docs: explain local HTTPS setup
refactor(auth)!: replace session tokens with JWTs
BREAKING CHANGE: clients must send Authorization: Bearer <token>.The format is type(optional scope): description. feat and fix are defined by the spec; docs, refactor, test, build, ci, chore and perf are common conventions. A ! after the type, or a BREAKING CHANGE: footer, marks a breaking change.
The reason to bother is automation. Release tools read the history and decide the next semantic version: a fix means a patch release, a feat a minor release, and any breaking change a major release. They also generate the changelog from the subjects. Versioning and changelogs covers those tools. Linters such as commitlint, run in a commit-msg hook or in CI, keep everyone to the format.
One practical twist: many teams squash-merge pull requests, so all the commits on your branch become one commit on main whose message comes from the PR title (depending on repository settings). On those teams the PR title is the commit message that matters, and it is often the only thing the Conventional Commit check validates. Your branch commits still help your reviewers, but name the PR with the same care.
With Conventional Commits and automated releases, match each commit to the version bump it triggers from 2.4.1.
What never goes into history
Some things must never be committed, because history is forever and every clone has a copy:
- Secrets: API keys, passwords, private keys,
.envfiles. Bots scan public repos for keys within minutes. If one slips in, revoke and rotate it first; rewriting history is cleanup, not the fix. - Large binaries: videos, datasets, design files, build artefacts. Every clone downloads every version forever. If you genuinely need large files versioned, use Git LFS (
git lfs track "*.psd"writes a rule into.gitattributes), and check your host's storage limits. - Generated output and dependencies:
node_modules/,dist/,.venv/. They belong in.gitignore, which Git Basics introduced.
People make mistakes, so let tools check. Git hooks are scripts Git runs at points like pre-commit and commit-msg. A non-zero exit cancels the commit. Teams share hooks through a framework, because .git/hooks itself is not committed.
# Python teams: the pre-commit framework. Install once: pre-commit install
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0 # `pre-commit autoupdate` bumps these to the latest tags
hooks:
- id: check-added-large-files
- id: detect-private-key
- id: end-of-file-fixer
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.4
hooks:
- id: gitleaks # scans staged changes for secrets# JavaScript teams: husky runs hooks, lint-staged runs tools on staged files onlynpm install --save-dev husky lint-stagednpx husky init # creates .husky/pre-commitecho "npx lint-staged" > .husky/pre-commit# then in package.json: "lint-staged": { "*.{ts,tsx}": ["eslint --fix", "prettier --write"] }Running tools on staged files only keeps the hook fast, and a hook that takes 30 seconds is a hook people turn off. Remember that hooks are a convenience, not a guarantee: they run on the developer's machine and git commit --no-verify skips them. In the practice repo for this lesson, a hook blocked a commit containing SECRET_KEY=, and --no-verify let the same commit straight through. So CI must run the same lint, format and secret checks, and server-side protection (such as GitHub's secret scanning with push protection, where your organisation enables it) is the last line.
Commits that say who you are
Every commit records user.name and user.email. Use your work email for work repos, or your commits will not link to your work account and may break your company's policy. If you keep personal and work projects on one laptop, let Git switch automatically by folder:
[user]
name = Ada Example
email = ada@personal.example
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work[user]
email = ada@company.exampleAny repository inside ~/work/ now uses the work email; everything else uses the personal one. The rule applies to repositories, so git config user.email run in ~/work itself (not a repo) still shows the personal address. Note the trailing slash in gitdir:~/work/, which means "anything below this folder".
Signing proves a commit really came from you, since anyone can type your name into user.email. Git can sign with the SSH key you probably already have:
git config --global gpg.format sshgit config --global user.signingkey ~/.ssh/id_ed25519.pubgit config --global commit.gpgsign trueThen add the same public key to GitHub as a signing key (it is a separate key type from an authentication key, even for the same file). GitHub then shows a "Verified" badge on your commits, and repositories can require signed commits through branch protection. To verify signatures locally, Git also needs an allowed-signers file listing trusted keys (gpg.ssh.allowedSignersFile); without it, git log --show-signature cannot say whose key it is.
Set Git up once
A few settings remove daily friction. Each one is worth knowing, because interviewers and teammates will assume you have them:
git config --global init.defaultBranch main # new repos start on maingit config --global pull.rebase true # pull replays your commits instead of making merge commitsgit config --global push.autoSetupRemote true # first git push of a new branch just worksgit config --global rerere.enabled true # remember how you resolved a conflict and reuse itgit config --global diff.algorithm histogram # clearer diffs when code moves aroundgit config --global commit.verbose true # show the diff while writing the messagegit config --global fetch.prune true # drop remote branches that were deleted on the serverpush.autoSetupRemote means the first git push on a new branch creates and tracks origin/<branch> without -u origin <branch>. pull.rebase keeps your branch's history straight when teammates push to it, and Rebase, Merge and Squash explains when that matters. rerere (reuse recorded resolution) saves real time during long rebases where the same conflict comes back.
You finished a bug fix and a small refactor in the same session. Put a clean commit workflow in order.
- Tap the steps below in the right order.
- atomic commit
- A commit containing exactly one logical change, which builds and passes tests on its own.
- patch mode
git add -p: stage changes hunk by hunk instead of whole files.- imperative mood
- Writing the subject as a command ('Fix crash'), so it completes 'If applied, this commit will...'.
- trailer
- A
Key: valueline at the end of a commit message, such asCo-authored-by:or a ticket reference. - Conventional Commits
- A spec (1.0.0) for structured subjects like
feat(cart): ...that release tools use to pick a semver bump and write changelogs. - pre-commit hook
- A script Git runs before a commit is created. A non-zero exit cancels it. Skippable with
--no-verify, so CI repeats the checks. - commit signing
- Signing commits with an SSH or GPG key so hosts like GitHub can mark them Verified.