Best Practices
Intuition
Section titled “Intuition”The habits of effective developers: Git best practices are like the habits of a good housekeeper — they keep your repository clean, your history readable, and your team productive. Small commits, clear messages, and consistent workflows prevent the chaos that accumulates in messy repositories.
Why it matters: Following best practices prevents common disasters — losing work, introducing bugs through messy merges, and spending hours deciphering cryptic commit messages from six months ago.
The key insight: Write commit messages for your future self — when you are debugging at 2 AM, a clear commit message like “fix: handle null user in login flow” saves more time than any optimisation.
Recommended Global Configuration
Section titled “Recommended Global Configuration”## Identitygit config --global user.name "Your Name"git config --global user.email "you@example.com"
## Default branchgit config --global init.defaultBranch main
# Pull strategy: rebase instead of merge (cleaner history)git config --global pull.rebase true
# Rebase autosquash (for fixup workflow)git config --global rebase.autoSquash true
# Default editorgit config --global core.editor "vim"
# Credential cachinggit config --global credential.helper cache --timeout=3600
# Push: only push the current branchgit config --global push.default current
# Diff: use better diff algorithmgit config --global diff.algorithm histogram
# Rerere: remember conflict resolutionsgit config --global rerere.enabled truegit config --global rerere.autoupdate true
# Transfer: optimize for large reposgit config --global core.compression 9git config --global pack.threads 0
# Status: show submodule summarygit config --global status.submoduleSummary true
# Alias: common shortcutsgit config --global alias.co checkoutgit config --global alias.br branchgit config --global alias.ci commitgit config --global alias.st statusgit config --global alias.lg "log --oneline --graph --all"git config --global alias.last "log -1 HEAD"git config --global alias.unstage "restore --staged"git config --global alias.amend "commit --amend --no-edit"Commit Discipline
Section titled “Commit Discipline”The Atomic Commit Principle
Section titled “The Atomic Commit Principle”Each commit should represent one logical change. This means:
# Bad: one commit with unrelated changesgit add src/auth.c src/utils.c docs/README.mdgit commit -m "Various improvements"
# Good: separate commits for each logical changegit add src/auth.cgit commit -m "feat(auth): add JWT token validation"
git add src/utils.cgit commit -m "fix(utils): handle null pointer in string_split"
git add docs/README.mdgit commit -m "docs: update installation instructions"Why Atomic Commits Matter
Section titled “Why Atomic Commits Matter”| Reason | Explanation |
|---|---|
| Bisectability | git bisect can pinpoint the exact commit that introduced a bug |
| Revertibility | git revert <hash> undoes one specific change without affecting others |
| Reviewability | Reviewers can understand each change in isolation |
| Cherry-picking | Individual fixes can be cherry-picked to release branches |
| History archaeology | Future developers can understand why each change was made |
Staging Partial Changes
Section titled “Staging Partial Changes”Use git add -p to stage specific hunks of a file:
$ git add -p src/auth.c# Stage this hunk [y,n,q,a,d,/,s,e,?]?# y - stage this hunk# n - do not stage this hunk# s - split the hunk into smaller pieces# e - manually edit the hunk.gitignore Best Practices
Section titled “.gitignore Best Practices”What to Ignore
Section titled “What to Ignore”# Build artifacts/build//dist/*.o*.so*.dll*.exe
# Dependencies/node_modules//vendor/.venv/
# IDE.idea/.vscode/*.swp*.swo*~
# OS.DS_StoreThumbs.db
# Environment.env.env.local.env.*.local
# Secrets*.pem*.keycredentials.jsonWhat NOT to Ignore
Section titled “What NOT to Ignore”- Configuration files that others need (
.eslintrc.json``tsconfig.json). - Lockfiles (
package-lock.json``yarn.lock``Cargo.lock). .gitignoreitself.
Global .gitignore
Section titled “Global .gitignore”For files that should be ignored in all repositories (OS-specific files, editor files):
# Configure a global gitignore$ git config --global core.excludesfile ~/.gitignore_global
.DS_StoreThumbs.db*.swp.vscode/Security
Section titled “Security”Never Commit Secrets
Section titled “Never Commit Secrets”Secrets (API keys, passwords, tokens) should never be committed to a Git repository, even in private repos:
# Use environment variablesexport API_KEY="your-key-here"
# Or use a secrets manager# - HashiCorp Vault# - AWS Secrets Manager# - .env files (gitignored)Scan for Committed Secrets
Section titled “Scan for Committed Secrets”# Use git-secrets (AWS)$ git secrets --install$ git secrets --register-aws
# Use truffleHog (open source)$ trufflehog git file://.git --only-verifiedSigned Commits
Section titled “Signed Commits”Sign commits with GPG or SSH to verify authorship:
# GPG signing$ git config --global user.signingkey YOUR_GPG_KEY_ID$ git config --global commit.gpgsign true
# SSH signing (Git 2.34+)$ git config --global gpg.format ssh$ git config --global user.signingkey ~/.ssh/id_ed25519.pub$ git config --global commit.gpgsign truePerformance
Section titled “Performance”For Large Repositories
Section titled “For Large Repositories”# Partial clone (fetch only needed objects)$ git clone --filter=blob:none https://github.com/user/large-repo.git
# Shallow clone (limited history)$ git clone --depth=1 https://github.com/user/repo.git
# Sparse checkout (only specific directories)$ git clone --sparse https://github.com/user/monorepo.git$ cd monorepo$ git sparse-checkout set src/packages/core
# File system monitoring (Git 2.36+)$ git config core.fsmonitor true # Uses watchman or fsmonitor-watchmanOptimizing git status
Section titled “Optimizing git status”# Enable untracked cache$ git config core.untrackedCache true
# Enable fsmonitor for faster status (requires watchman)$ git config core.fsmonitor trueWorking with Worktrees
Section titled “Working with Worktrees”git worktree allows you to have multiple working directories from the same repository, each on a different branch:
# Create a worktree for a feature branch$ git worktree add ../feature-auth feature-auth
# Now you can work in both directories simultaneously$ cd ../feature-auth# ... make changes, commit ...$ cd ../main-repo# ... continue working on main ...Use cases:
- Run long tests on one branch while developing on another.
- Compare two branches side-by-side in your IDE.
- Hotfix production while continuing feature work.
# List worktrees$ git worktree list
# Remove a worktree$ git worktree remove ../feature-authCommon Aliases
Section titled “Common Aliases”# Shortcutsgit config --global alias.co checkoutgit config --global alias.br branchgit config --global alias.ci commitgit config --global alias.st status
# Enhanced loggit config --global alias.lg "log --oneline --graph --all --decorate"
# Show the last commitgit config --global alias.last "log -1 HEAD --stat"
# Diff staged changesgit config --global alias.dc "diff --cached"
# Unstage a filegit config --global alias.unstage "restore --staged"
# Amend without editing messagegit config --global alias.amend "commit --amend --no-edit"
# Show which branches contain a commitgit config --global alias.contains "branch --contains"
# Quick stash with messagegit config --global alias.save "stash push -m"Common Pitfalls
Section titled “Common Pitfalls”Neglecting to normalise database designs, leading to data redundancy and update anomalies.
Confusing an algorithm with a program. An algorithm is a step-by-step procedure, not its implementation in code.
Writing pseudocode that is too language-specific rather than using standard algorithmic constructs.
Forgetting that average-case for quicksort becomes worst-case on already sorted input.
Summary
Section titled “Summary”The key principles covered in this topic are linked in the sub-pages above. Focus on understanding the definitions, applying the formulas or frameworks, and evaluating strengths and limitations of each approach.
Worked Examples
Section titled “Worked Examples”Worked examples demonstrating the application of key concepts are covered in the detailed sub-pages linked above.