Git Best Practices: Commits, Branches, Reviews and Repository Hygiene
The habits experienced teams rely on: small focused commits with clear messages, short-lived branches, keeping up with main, when to rebase and when to merge, safe force pushes, useful reviews, protected branches, keeping secrets and build output out, and a quick repository health check.
kvi5hnuCode Sprout team member8 min readOn this page
Git lets you work in almost any way, which is why teams that use it well agree on a few habits. None of these are rules Git enforces. They're the conventions that make history readable, reviews quick, and mistakes rare and easy to undo. This article collects them in one place, with links to the articles that cover each in depth.
Commits
One logical change per commit. A commit should do one thing: fix a bug, add a feature, rename a function. Don't mix a refactor, a fix and a formatting change in one commit. Focused commits are easier to review, revert, cherry-pick and bisect, and blame makes more sense when each line's commit explains it.
- Stage selectively with
git add -pto split mixed work into separate commits (article 5). - Commit often while working, then tidy up with interactive rebase before sharing: squash "fix typo" commits into the commits they fix, and reorder (article 15).
git commit --fixup=<commit>withgit rebase --autosquashmakes this nearly automatic. - Every commit should build and pass tests, so that
git bisectcan test any of them (article 31).
Write messages for the next reader, often yourself in a year (article 6):
Fix distance rounding on trail pages
Distances were truncated to whole kilometres, so 5.4 km showed as
5 km. Round to one decimal place instead, and add tests for values
just below and above the halfway point.
Fixes #142
- A subject line of about 50 characters, in the imperative ("Fix", "Add", not "Fixed" or "Adds"), with no full stop.
- A blank line, then a body explaining why the change was made and anything surprising. The diff already shows what changed.
- References to issues, and trailers such as
Co-authored-by:where your team uses them. Some teams follow Conventional Commits (fix:,feat:), which tools can turn into changelogs.
Branches
- Keep branches short-lived. A branch that lives for days merges easily. One that lives for months becomes a painful merge. Merge small, finished steps, and hide incomplete features behind feature flags if needed (article 22).
- Name branches clearly:
fix/rounding-142,feature/ridge-map. Use the prefixes your team agrees on. - Stay current with
main. Rebase your private branch ontomain, or mergemaininto it, regularly, so conflicts stay small (articles 12 and 14). - Delete merged branches, locally and on the server, to keep the list meaningful (article 23). Most hosts can do it automatically after a merge.
- Never commit directly to
mainin a team: use pull requests, and protect the branch.
Rebase or merge?
| Situation | Usual choice |
|---|---|
updating your own unpushed or private branch with main | rebase: linear history, no noise merges |
integrating a finished feature into main | merge (or squash merge) through a pull request, as your team prefers |
| a branch others have pulled and built on | merge, never rebase, unless everyone agrees |
pulling the latest main with no local commits | fast-forward only: git pull --ff-only, or pull.ff=only |
Don't rewrite shared history. If you must force push, for instance your own pull request branch after a rebase, use git push --force-with-lease (and --force-if-includes), which refuses if someone else pushed in the meantime (article 20).
Reviews and pull requests
- Keep pull requests small: a few hundred changed lines at most. Large ones get skimmed rather than reviewed. Split big features into a series.
- Describe the change: what, why, how to test, and screenshots for user-facing changes. Link the issue.
- Review your own diff first.
git diff main...HEAD(article 7) often catches leftover debugging code and unrelated changes. - Let automation catch the routine problems: formatting, linting, tests and secret scanning in CI and hooks (article 36), so reviews focus on design and correctness.
- After review changes, either add fixup commits and squash them before merging, or rebase and force push with lease.
git range-diffshows reviewers exactly what changed (article 45).
Protecting the main branch
On your hosting service, enable branch protection (or rulesets) for main and release branches:
- require pull requests, with at least one approving review
- require CI status checks to pass, and the branch to be up to date
- block force pushes and deletion
- optionally require signed commits (article 39) and linear history
- use a
CODEOWNERSfile to request reviews from the right people automatically
Repository hygiene
- Never commit secrets. Use environment variables or a secrets manager, ignore
.envfiles, and enable the host's secret scanning and push protection. If a secret gets in, rotate it first (article 47). - Don't commit generated files: build output, dependencies (
node_modules/), logs and editor settings. Ignore them, and keep personal ignores in a global ignore file or.git/info/exclude(article 8). - Put large binaries in Git LFS, or outside Git entirely (article 43).
- Add
.gitattributesfor line endings and binary files, so Windows, macOS and Linux users don't fight over CRLF (article 35). - Tag releases with annotated, ideally signed, tags (article 38).
- Keep a README on how to clone, build and contribute, including any Git setup, such as LFS, submodules or hooks.
A quick health check
These commands find the most common problems in an existing repository:
git init -q trail-guide && cd trail-guide
echo "Lake loop" > lake.txt; mkdir build; echo "binary" > build/app.o; echo "API_KEY=abc" > .env
git add .; git commit -q -m "Add lake page and everything else"
printf 'build/\n.env\n' > .gitignore; git add .gitignore; git commit -q -m "Ignore build output and env"
git commit -q --allow-empty -m "fixed stuff"
git commit -q --allow-empty -m "Add the ridge loop page with its distance, elevation profile and parking information"
echo "Ridge loop " > ridge.txt; git add ridge.txt
echo "=== tracked files that the ignore rules match"
git ls-files -ci --exclude-standard
echo "=== whitespace problems in staged changes"
git diff --cached --check
echo "=== subjects that are too long or too vague"
git log --format=%s | awk 'length > 50 || /^(fix|fixed|wip|stuff|update)( |$)/ {print length ": " $0}'
=== tracked files that the ignore rules match
.env
build/app.o
=== whitespace problems in staged changes
ridge.txt:1: trailing whitespace.
+Ridge loop
=== subjects that are too long or too vague
84: Add the ridge loop page with its distance, elevation profile and parking information
11: fixed stuff
git ls-files -ci --exclude-standardlists tracked files that match ignore rules: files committed before the rule was added. Here that's an.envfile with a key, which should be rotated, untracked withgit rm --cached, and possibly removed from history.git diff --checkreports trailing whitespace and conflict markers, and is worth running in a pre-commit hook.- Scanning subjects finds messages to improve in future, though not to rewrite in shared history.
Day-to-day habits
- Run
git statusoften, and read what it says: it suggests the next command for most situations. - Fetch before you start work, and look at what changed:
git log --oneline HEAD..origin/main. - Commit before risky operations. Committed work can almost always be recovered through the reflog. Uncommitted work can't (article 26).
- Use
git switchandgit restorerather than the overloadedcheckout(articles 11 and 24). - Configure Git once, properly: name, email, default branch,
pull.rebaseorpull.ff,rerere, a global ignore file, and aliases for frequent commands (articles 33 and 34).
What's current
- Hosting services have moved from classic branch protection to rulesets, which apply rules across many branches and repositories.
- Secret scanning with push protection is widely available and blocks many leaks before they reach the server.
- Merge queues test pull requests together with the latest
mainbefore merging, which keepsmaingreen on busy repositories.
Common questions
Should we squash merge every pull request?
It's a team choice. Squash merging gives one commit per pull request on main, which is tidy but loses the individual commits. Merge commits keep them, which helps bisect and blame when commits are well made. Rebase merging keeps them in a straight line. Pick one, and configure the host to allow only that.
How small is "small" for a commit? Small enough that its message can describe it in one subject line without "and". A commit that renames a function across 80 files is fine. It's one logical change.
Is it bad to have many "WIP" commits on my branch?
Not while you work. Clean them up before the branch is reviewed or merged, with interactive rebase or a squash merge, so main tells a clear story.
What should never go into a repository? Secrets and credentials, personal data, build outputs and dependencies, large binaries outside LFS, and machine-specific settings.
Summary
- Commit one logical change at a time, with a short imperative subject and a body explaining why. Every commit should build.
- Keep branches short-lived and current, delete them after merging, and never commit to
maindirectly. - Rebase private work, merge shared work, and force push only with
--force-with-lease. - Keep pull requests small and described, review your own diff first, and let CI and hooks handle routine checks.
- Protect
main, keep secrets, build output and large binaries out, and add.gitignoreand.gitattributesfrom the start.
Practice questions
Your working tree contains a bug fix, a refactor of an unrelated function, and reformatting of a file. How do you commit it?
Answer
As three separate commits. Use git add -p to stage only the bug fix's hunks, commit with a clear message, then do the same for the refactor and the formatting. Each commit can then be reviewed, reverted or cherry-picked on its own, and git bisect lands on the commit that actually caused a problem.
You rebased your pull request branch onto the latest main. How do you update the pull request safely?
Answer
git push --force-with-lease, ideally with --force-if-includes. It replaces the remote branch only if it still holds what you last fetched, so a teammate's commits pushed in the meantime aren't silently overwritten. Then tell reviewers, or let git range-diff show what changed.
git ls-files -ci --exclude-standard lists config/secrets.yml. What does it mean, and what should you do?
Answer
The file is tracked, even though an ignore rule now matches it, because ignore rules don't affect files already committed. First, rotate any credentials it contains. Then stop tracking it with git rm --cached config/secrets.yml and commit. If it was pushed, consider removing it from history with filter-repo (article 47).
Previous: Migrating to Git From Subversion, TFVC and Mercurial

More in Git Course
Quiz: Git Delicate Details
Twenty-five questions on Git's subtle corners: what commit -a and stash leave out, empty folders, ignore patterns and negation, HEAD~ versus HEAD^, ours and theirs in a rebase, tags that don't move or don't push, describe, merge reverts, diff exit codes, stash conflicts and more.
Quiz: Git Interview Questions
Thirty Git questions of the kind asked in developer interviews: Git versus GitHub, the staging area, merge versus rebase, fetch versus pull, reset, revert and restore, detached HEAD, conflicts, force pushing, stash, cherry-pick, reflog, bisect, submodules, LFS and how commits are identified.
Quiz: Git Course Final Exam (All Parts)
The final exam for the Git course: thirty questions across all twelve parts, from the three areas and staging through branching, remotes, undoing, history investigation, configuration, tags, larger projects, patches, rewriting, internals and troubleshooting.
Quiz: Professional Git Practice (Git Part 12)
Sixteen questions on migrating to Git from Subversion, TFVC and Mercurial, team best practices for commits, branches and reviews, repository hygiene, and diagnosing and fixing the most common Git errors, with explanations.
Discussion
Sign in to ask a question or share what you learned.