Skip to content
notes.vinhnq.com

Search

Git, DevOps & ToolingJunior13 min read

Git: version control, the staging area, the object model and commit conventions

Review 10 cards
On this page

Git series: 1. Commits and the object model · 2. Remotes, tags and backups · 3. Branching, merge, rebase and PRs

Copying the project folder to project-v1, project-final, project-final-really… wastes space and tells you nothing about who changed what or how to go back; add a second developer and it collapses. This post covers Git’s foundations on your own machine: the three areas, the object model underneath, writing decent commits, and everyday undo. Remotes, cloning, the daily push habit and release tags are in part 2; branches, merges, rebases, conflicts, the reflog and pull requests are in part 3.

1. Version control and Git

Key idea: a version control system (VCS) tracks changes to a set of files over time. Git is the most widely used distributed VCS: every clone carries the full history.

A VCS lets you:

  • Save and label versions (tags, releases) and look at the code as it was at any earlier version.
  • Compare (diff) two versions and undo changes.
  • Find out who changed a line, when, and why (git blame, commit messages).

Repository

Key idea: a repository (repo) is the code plus its full history, stored in the .git directory. Delete .git and the history is gone, although your current files stay.

Usually one repo maps to one application. The exception is a monorepo: many services in a single repo, as Google and Meta do.

mkdir booking-service && cd booking-service
git init            # creates the .git directory, which IS the repo
git init -b main    # name the default branch main (Git >= 2.28)

2. The commit workflow: Git’s three areas

Key idea: you edit files in the working directory, pick which changes go into the commit with git add (moving them to the staging area), then git commit packages exactly what is staged into a point in history.

Unlike “Save” (one file), a commit bundles changes across many files with an author, a timestamp and an explanation. After touching a dozen files it’s hard to remember which change belongs where, hence the staging area (also called the index): you move finished changes into it as you work.

flowchart LR
  WD[Working directory<br/>files on disk] -- git add --> SA[Staging area<br/>index]
  SA -- git commit --> REPO[(Repository<br/>chain of commits)]
  REPO -- git restore / git switch --> WD
  SA -->|"git restore --staged"| WD
  • Working directory: the files you see and edit.
  • Staging area: the draft of your next commit.
  • Repository: the chain of commits; each git commit appends a new one.
git status                 # what's modified, what's staged, what's untracked
git add src/Hotel.java     # stage one file
git add .                  # stage everything under the current directory
git add -p                 # stage hunk by hunk: a senior favourite for clean commits
git diff                   # working directory vs staging
git diff --staged          # staging vs last commit (what you're about to commit)
git commit -m "feat(hotel): add search by city"
git log --oneline --graph --decorate

Every commit has a hash (a 40-character SHA-1 such as a1b2c3d...; Git is gradually adding SHA-256 support). It’s computed from the content, so changing one byte gives a different hash.

3. Under the hood: the object model

Key idea: Git is a content-addressable store (a key-value store where the key is the hash of the content and the value is the compressed content). A commit points to a tree (a directory), a tree points to blobs (file contents), and a branch is just a pointer to a commit.

The slides skip this, but it’s a classic senior interview question. There are four object types:

Object Holds
blob The contents of a file (no file name)
tree A list of name → blob/tree entries with modes, i.e. a directory
commit A pointer to a root tree + parent commits (0, 1 or more) + author, committer, timestamps, message
tag (annotated) A pointer to another object, with a tagger, a message and an optional GPG signature
flowchart TB
  C2[commit c2<br/>feat: add room] --> C1[commit c1<br/>init]
  C2 --> T2[tree /]
  T2 --> B1[blob README.md]
  T2 --> T3[tree src/]
  T3 --> B2[blob Hotel.java]
  T3 --> B3[blob Room.java]
  C1 --> T1[tree /]
  T1 --> B1
  MAIN([refs/heads/main]) --> C2
  HEAD([HEAD]) --> MAIN

Four consequences:

  • A commit is a snapshot, not a diff. Unchanged files reuse the exact same blob, so the repo doesn’t double in size. Later, Git also packs objects into packfiles using delta compression.
  • History is immutable. A commit’s hash depends on its parent’s hash. “Editing” an old commit (amend, rebase) really creates a new commit; the old one stays until garbage collection.
  • A branch is a tiny file holding a hash. refs/heads/main is a 41-byte text file, so creating a branch costs almost nothing.
  • HEAD points to the current branch, or directly at a commit (detached HEAD).
Commands to inspect the object model
echo "hello" | git hash-object --stdin   # prints the blob hash
git cat-file -t HEAD                     # commit
git cat-file -p HEAD                     # shows tree, parent, author...
git cat-file -p HEAD^{tree}              # lists the root directory
cat .git/HEAD                            # ref: refs/heads/main
cat .git/refs/heads/main                 # a hash

4. Commit conventions and commit hygiene

Key idea: write messages in the Conventional Commits format (type(scope): description) so both people and tools can read them. Keep each commit to one idea, building and passing tests.

<type>[optional scope]: <description>

[optional body]

[optional footer(s)]

type is the kind of change (feat, fix, refactor…), scope is the domain affected (user, booking, payment), and description is a short summary.

Full type table and example messages
type Use it for
feat A new user-facing feature
fix A bug fix
refactor Restructuring code without changing behaviour
perf Performance improvements
style Formatting, whitespace, semicolons: no logic change
test Adding or fixing tests
docs Documentation
build / ci Build tooling, dependencies, pipelines
chore Other housekeeping (cleanup, config)

My own examples:

feat(booking): reject bookings with checkout before checkin
fix(hotel): return 404 instead of 500 when hotel id is unknown
refactor(search): extract price calculation into PricingService
feat(api)!: rename /hotels/search to /hotels

BREAKING CHANGE: clients must call GET /api/v1/hotels with query params.

Commit hygiene: what a senior notices when reading someone’s history.

  1. One commit, one idea. Don’t mix “fix the bug” with “rename a variable everywhere”; split with git add -p.
  2. Every commit builds and passes tests, which is what makes git bisect (finding the commit that broke something by halving the history) usable.
  3. Imperative subject line, roughly 72 characters max: “add”, not “added” or “adding”.
  4. The body explains why; the diff already shows what.
  5. Never commit secrets. If one gets pushed, treat it as leaked: rotate it first, then scrub history (git filter-repo).
  6. Clean up “wip” and “fix typo” commits before opening the PR (interactive rebase or squash), not after it’s merged.

5. Everyday undo: restore and amend

Key idea: before pushing, git restore discards or unstages changes and git commit --amend fixes the last commit. Once pushed, add a follow-up commit instead of amending.

git restore src/Hotel.java            # discard unstaged changes to the file (gone for good, be careful)
git restore --staged src/Hotel.java   # unstage the file; the changes stay in the working directory
git commit --amend                    # fix the last commit: add a forgotten file, reword the message
git commit --amend --no-edit          # fold the staged changes into the last commit, keep the message

--amend creates a new commit that replaces the last one (new hash, exactly as the object model in section 3 predicts).

Exercises

Exercise 1 (my own): Verify the object model yourself

Task: Show with commands that (a) a commit is a snapshot, yet an unchanged file isn’t stored a second time, and (b) a branch is just a file holding a hash.

Solution to Exercise 1
git init -b main objects-lab && cd objects-lab
echo "hello" > a.txt && echo "world" > b.txt
git add . && git commit -qm "first"
echo "world v2" > b.txt
git commit -qam "second"

git rev-parse HEAD:a.txt HEAD~1:a.txt     # two IDENTICAL hashes: a.txt didn't change, so one blob is reused
git rev-parse HEAD:b.txt HEAD~1:b.txt     # two DIFFERENT hashes: b.txt changed, so there is a new blob
git cat-file -p HEAD                      # tree + parent + author: a commit points to a whole tree, not a diff
cat .git/refs/heads/main                  # same hash as the next command prints
git rev-parse HEAD
git count-objects -v                      # count: 7

Result: two commits produce just 7 objects: 3 blobs (hello, world, world v2), 2 trees and 2 commits. a.txt appears in both snapshots but has a single blob, because the same content means the same hash. That’s why “commits are snapshots” doesn’t double the size of the repo.

Remember

  • Can you name Git’s three areas and the command that moves changes between them (add, commit, restore, restore --staged)?
  • Can you explain why commits are snapshots yet the repo doesn’t double in size?
  • Can you say what a branch and HEAD really are, and why amend/rebase change hashes?
  • Do you know when amending is fine and when you must add a fix-up commit?
  • Do you know the first thing to do after pushing a secret?

Interview questions

Junior

What does git commit --amend do, and when shouldn’t you use it?

It replaces the last commit with a new one; don’t use it on a commit already pushed to a branch others use.

The new commit contains whatever is staged plus the (optionally edited) message. Since a commit’s hash depends on its content, amending always changes the hash. Amend a pushed commit and your history and the remote’s diverge, you have to force push, and everyone else ends up out of sync. Once it’s pushed, add a fix-up commit instead.

What’s the difference between Git and GitHub?

Git is a version control tool that runs on your machine; GitHub is a hosted service for Git repos.

GitHub adds pull requests, issues, CI (Actions) and access control. You can use Git without GitHub (GitLab, Bitbucket, or a self-hosted server).

What is the staging area for?

It’s the draft of your next commit: it lets you pick exactly which changes go in.

You can pick down to individual hunks with git add -p, so one messy editing session can still become several focused commits.

Mid

Does a commit store a snapshot or a diff? Then why doesn’t the repo blow up in size?

A snapshot; the repo stays small because an unchanged file has the same hash and reuses the existing blob.

Each commit points to a root tree describing the whole directory; only changed files produce new blobs. Later, git gc packs objects into packfiles with delta compression between similar versions. Diffs aren’t stored at all; they’re computed when you run git diff or git log -p.

What do Conventional Commits give you beyond a readable history?

They’re machine-readable: tools work out the next version and generate the changelog.

With semantic-release or release-please, fix bumps the patch, feat the minor, ! or BREAKING CHANGE the major. Filtering history by type or scope is trivial. You can enforce the convention with commitlint in a hook or in CI. Combined with “one commit, one idea”, reverts and bisects get more precise too.

Senior

Explain Git’s object model. What is a branch, really?

Git is a content-addressable store of blobs, trees, commits and annotated tags; a branch is just a ref, a file holding the hash of the tip commit.

A blob is file contents, a tree is a directory mapping names to blobs and trees, and a commit points to a root tree, parent commits and metadata. Each object is identified by the hash of its content. A commit is a snapshot of the whole tree, and unchanged files reuse existing blobs. HEAD points to the current branch. Because a commit’s hash includes its parent’s, rewriting history always produces new commits.

An API key was pushed to main. What do you do?

Assume it’s leaked and rotate or revoke it immediately: that’s the most important step, because clones, forks and CI caches may already have it.

  • Remove it from the code and move it to a secret manager or environment variable.
  • If it must leave history too, use git filter-repo or BFG, coordinate a force push with the whole team, and ask the host (GitHub) to purge cached views.
  • Prevent it next time with secret scanning, a pre-commit hook (gitleaks) and .gitignore entries for .env files.

Useful phrases for interviews

  • “I use git add -p to stage hunk by hunk, so each commit tells one story.”
  • “Under the hood, a commit is a snapshot of the entire tree, and a branch is just a pointer to a commit.”
  • “I try to keep each commit focused on one change so the history stays bisectable.”
  • “When a secret leaks, rotating it comes first. Cleaning the history is secondary.”
  • “Conventional commit messages let semantic-release work out the next version and the changelog for us.”
  • “Commit subjects go in the imperative mood, like ‘add retry to the payment client’, and the body explains why.”
  • “I only amend commits I haven’t pushed yet; after that, I add a fix-up commit instead.”

Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.