Git
Version Control

Git

A complete guide to Git, covering distributed version control, internal architecture (blobs, trees, commits), the staging area, and daily workflows.

Have you ever worked on a project and ended up with a folder full of files like Project_Draft.docx, Project_Final.docx, Project_Final_v2.docx, and Project_Final_REALLY_FINAL.docx? Now imagine twenty software engineers collaborating on the exact same codebase at the same time: editing the same files, deleting lines of code, and adding new features. Without a dedicated tool to track who changed what, when, and why, working together quickly becomes chaotic. Files get overwritten, working code gets accidentally deleted, and nobody knows which version is safe to deploy. Git was created in 2005 by Linus Torvalds, the creator of Linux, to solve this problem. Git is a Distributed Version Control System (DVCS). It acts like a time machine for your code, recording snapshots of every change in your project's history. It lets you review past versions, experiment safely in isolated branches, and combine different teammates' work smoothly.

Definition

Git is a distributed version control system that tracks changes in computer files over time, enabling multiple developers to work together asynchronously while maintaining a verifiable history of every change.

Why It Matters

Git is the foundation of modern software engineering and DevOps workflows. Almost all software teams use Git daily. Key practices like Continuous Integration (CI), Infrastructure as Code (IaC), and GitOps rely on Git as the single source of truth for both application and infrastructure code. Git matters because it gives developers the freedom to experiment without fear. You can rewrite an entire module or test an ambitious new idea: if it does not work out, a single command restores your project to the exact state it was in earlier.

How It Works

Under the hood, Git does not just track line-by-line differences; it functions like a mini filesystem of snapshots. Everything in Git is stored inside the hidden .git/ directory and identified by a cryptographic hash based on the content: 1. The Core Git Objects: • Blobs (Binary Large Objects): Stores the raw content of a file. A blob only contains the file's data, without its filename or directory location. • Trees: Represents folders. A tree object lists filenames, file permissions, and pointers to the blobs or other sub-trees inside that folder. • Commits: Represents a snapshot of the project at a point in time. A commit points to a top-level root tree and records the author, timestamp, commit message, and parent commit. • Annotated Tags: A permanent pointer to a specific commit, often used to mark version releases (such as v1.0.0). 2. The Three Trees Architecture: • Working Directory: Your active folder on disk where you create and edit files. • Staging Area (The Index): A preparation area where you organize changes using git add. This allows you to choose exactly which changes belong in your next commit. • Git Repository (HEAD): The permanent database in .git where committed snapshots are safely stored. 3. Distributed vs Centralized Version Control: In older centralized systems (like SVN), a central server held the only full history. If the server went down or you had no internet access, you could not commit or view previous logs. In Git, every local clone is a complete backup of the entire project history, meaning you can commit, view logs, and create branches completely offline.

Git Architecture: The Three Trees and Object Flow

1. Working Directory
Your actual project files on disk; edits here are initially modified or untracked
2. `git add <file>`
Compresses the file content into a Blob object in `.git/objects/` and updates the Index
3. Staging Area (The Index)
The staging file (`.git/index`) containing the exact snapshot prepared for the next commit
4. `git commit -m '...'`
Creates a Tree and a Commit object pointing to its parent, then moves the branch pointer forward
5. Local Repository (`HEAD`)
The commit snapshot is now permanently recorded in your local repository
6. `git push origin`
Uploads the new commit objects over the network to the shared remote repository

Key Points

  • Git stores snapshots of files over time, not just lists of changes.
  • Commits are content-addressed: if any file content or metadata changes, its unique SHA hash changes.
  • The Staging Area gives you precise control over what enters each commit.
  • Git is fully distributed: every developer has a full copy of the project's history locally.
  • Branches in Git are lightweight pointers that move forward as new commits are created.

Steps

  1. Initialize a Repository

    Run `git init` in your project folder to create the hidden `.git` directory that holds project history.

  2. Configure Your Identity

    Set your name and email with `git config --global user.name 'Your Name'` and `git config --global user.email 'you@example.com'`.

  3. Check Repository Status

    Use `git status` frequently to see which files are modified, staged, or untracked in your working tree.

  4. Stage and Commit Your Changes

    Use `git add <file>` to stage related changes, then create a snapshot with `git commit -m 'clear description of change'`.

  5. Sync with a Remote Host

    Connect your local project to a remote host (like GitHub or GitLab) with `git remote add origin <url>` and push your commits.

Examples

The Video Game Checkpoint Analogy

Working on software without Git is like playing a long video game with only one save slot: if you make a mistake or get stuck, your progress is ruined. Git gives you unlimited save checkpoints. Before trying a major refactor, you save your progress with a commit. If something goes wrong, you can reload your earlier checkpoint in seconds.

Real-World Examples

Linux Kernel Development

The Linux kernel is one of the largest collaborative projects in the world, with tens of millions of lines of code and contributions from thousands of developers worldwide. Git was originally created specifically to handle the speed, scale, and distributed nature of Linux development without slowing down.

Technical Examples

Exploring Git Internal Objects with Low-Level Commandsbash
# ─── Exploring Git's Object Database ──────────────────────────────

# 1. Create a temporary scratch repository
git init /tmp/git-demo && cd /tmp/git-demo

# 2. Store content directly into Git's object store (creates a Blob)
echo "Hello, DevOps World!" | git hash-object -w --stdin
# Output: e7a5fa0be7d9f7a7509f6b95b87a829e0617ad73 (40-character SHA-1)

# 3. Check the object type and view its content
git cat-file -t e7a5fa0be7d9f7a7509f6b95b87a829e0617ad73
# Output: blob

git cat-file -p e7a5fa0be7d9f7a7509f6b95b87a829e0617ad73
# Output: Hello, DevOps World!

# 4. View where Git stored the object on disk:
ls -la .git/objects/e7/
# Shows the compressed object file named after the rest of the hash
This demonstration shows how Git stores data internally. The `git hash-object` command hashes and compresses content into `.git/objects/`. The first 2 characters of the hash become the folder name, and the remaining 38 characters become the filename.

Distributed VCS (Git) vs Centralized VCS (SVN, CVS)

AspectDistributed VCS (Git)Centralized VCS (SVN, CVS)
Repository StorageEvery local clone contains the full project historyOnly the central server contains the full history
Offline WorkFull functionality: commit, branch, and view logs offlineRequires an active network connection to the server
Branching SpeedNearly instantaneous, creating a small pointer fileSlower, often copying directory trees on the server
Single Point of FailureNone: every developer's machine acts as a backupServer downtime stops the team from committing
SpeedVery fast because most commands run against local diskDependent on network speed for everyday operations

Porcelain vs Plumbing Commands

Git commands are divided into two main layers: • Porcelain Commands: Everyday user-friendly commands designed for developers (`git commit`, `git checkout`, `git pull`, `git merge`). • Plumbing Commands: Low-level utility commands designed for scripts and internal execution (`git hash-object`, `git cat-file`, `git ls-tree`, `git write-tree`). Understanding plumbing commands helps demystify Git: when you run a simple `git commit`, Git behind the scenes creates blobs for changed files, writes a tree object reflecting your folder structure, and creates a commit pointing to that tree.

Advantages

  • Cryptographic Integrity: Content-based hashing ensures that history cannot be changed or corrupted without detection.
  • Full Offline Capability: You can commit, create branches, and review logs without an internet connection.
  • Fast Performance: Most everyday commands work directly with local disk storage.
  • Universal Support: Supported by all major code hosting services, development environments, and CI/CD tools.

Limitations

  • Initial Learning Curve: Git's commands and concepts can take time for beginners to master.
  • Large Binary Files: Git is optimized for text and source code; storing very large media or dataset files directly can bloat the repository without tools like Git LFS.

Interview Questions

Explain how a Git commit is structured internally.

A Git commit object contains metadata about a specific snapshot: author name and email, timestamp, commit message, one or more parent commit hashes, and a pointer to a root Tree object. The Tree object represents the top-level directory and points to other Tree objects (subfolders) or Blob objects (file contents). If a file has not changed between commits, Git simply points to the existing Blob hash rather than creating a duplicate.

Practice Questions

  1. Run `git cat-file -p HEAD` in a local repository to see the raw contents of your most recent commit object.
  2. Set up a `.gitignore` file for a project to make sure build outputs, temporary files, and local environment files are not committed.