The .git Directory Structure

Understand common Git metadata such as HEAD, refs, objects, and index, while accounting for worktrees, packed refs, and alternate repository layouts.

published: reading time: 22 min read author: Geek Workbench updated: November 17, 2026
Quick Summary

Git metadata usually lives in a .git directory, but linked worktrees, separate gitdirs, packed refs, and reftable can change where state is stored. Use Git commands to inspect the actual paths and treat diagrams of loose files as typical examples, not a fixed layout.

Introduction

Most non-bare Git repositories keep metadata in a .git directory. In a linked worktree, .git is usually a small file that points to a per-worktree Git directory, which in turn refers to a shared common directory. Separate Git directories and object-store alternates can also change where data lives. Use Git’s inspection commands instead of assuming .git is one fixed folder.

Git organizes repository metadata into files, directories, references, and caches. A .git directory is the common layout, though linked worktrees can point to per-worktree and shared Git directories.

This post covers common components, explains what they do, and shows how their storage can vary across repository layouts.

When to Use / When Not to Use

When to understand .git internals:

  • Recovering from corrupted repositories or lost commits
  • Debugging mysterious Git behavior (detached HEAD, missing branches)
  • Writing custom Git hooks or tooling
  • Optimizing large repositories
  • Understanding how Git achieves its guarantees

When not to dig into .git:

  • Daily development workflows — use normal Git commands
  • When you’re unsure — modifying .git files directly can corrupt your repo
  • For simple tasks like committing or branching — the CLI is sufficient

Core Concepts

The Git directory holds repository metadata; it is separate from the working tree, but it may be linked to a common directory shared with other worktrees. Git also supports different ref and object storage formats, so treat the layout below as a map of common files rather than a complete specification.


graph TD
    A[".git Directory"] --> B["HEAD"]
    A --> C["config"]
    A --> D["objects/"]
    A --> E["refs/"]
    A --> F["hooks/"]
    A --> G["index"]
    A --> H["logs/"]
    A --> I["description"]
    A --> J["packed-refs"]
    A --> K["COMMIT_EDITMSG"]

    D --> D1["info/"]
    D --> D2["pack/"]
    D --> D3["<object-ID prefix>/"]

    E --> E1["heads/"]
    E --> E2["tags/"]
    E --> E3["remotes/"]

The filesystem examples are useful for learning, but Git commands should remain the normal way to inspect or repair repository state. Linked worktrees use per-worktree and common directories; refs may be loose files, packed into packed-refs, or stored with the reftable backend. Repository format and extensions can add further variation. See the official repository layout, worktree, and reftable documentation.

Architecture or Flow Diagram


flowchart LR
    WT["Working Tree\n(your files)"] -->|git add| IDX["index\n(staging area)"]
    IDX -->|git commit| OBJ["objects/\n(blobs, trees, commits)"]
    OBJ -->|referenced by| REF["refs/\n(branches, tags)"]
    REF -->|pointed to by| HD["HEAD\n(current ref)"]
    HD -->|determines| WT

    CFG["config"] -.->|settings| IDX
    CFG -.->|settings| OBJ
    HKS["hooks/"] -.->|triggers| IDX
    HKS -.->|triggers| OBJ

The flow shows how data moves from your working tree through the staging area into the object database, with references and HEAD tracking the current state. Configuration and hooks influence every transition.

Read-Only Inspection

Use Git to find the metadata paths and list refs. In a linked worktree, the Git directory and common directory can differ:

git rev-parse --show-toplevel
git rev-parse --absolute-git-dir
git rev-parse --git-common-dir
git rev-parse --git-path objects
git show-ref --head

The following settings may be absent when a repository uses defaults:

git config --get core.repositoryformatversion
git config --get extensions.objectFormat
git config --get extensions.refStorage

These commands inspect repository state; they do not require editing .git files.

Step-by-Step Guide / Deep Dive

Core References

The HEAD File

HEAD is a single file containing a reference to the current branch or a commit object ID:


$ cat .git/HEAD
ref: refs/heads/main

When HEAD is detached, it contains an object ID instead of a symbolic branch reference. The ID’s format follows the repository’s hash algorithm.

The config File

Your repository’s local configuration, overriding global (~/.gitconfig) and system-level settings:


[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = https://github.com/user/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
    remote = origin
    merge = refs/heads/main

Object Storage

The objects/ Directory

The object database stores blobs, trees, commits, and tag objects by object ID. In a linked worktree, this storage normally belongs to the common Git directory; alternates can also supply objects:


$ ls .git/objects/
02/  0a/  1b/  2c/  3d/  ...  pack/  info/

The loose-object path uses an object-ID prefix as a subdirectory and the remaining characters as the filename. The ID length depends on whether the repository uses SHA-1 or SHA-256; Git may also read objects from an alternate object store.

The refs/ Directory

References are named pointers to commits:


refs/
├── heads/        # Local branches
│   ├── main
│   └── feature/auth
├── tags/         # Tags
│   └── v1.0.0
└── remotes/      # Remote-tracking branches
    └── origin/
        ├── main
        └── develop

In the files ref backend, a loose ref contains an object ID; SHA-1 repositories use 40 hexadecimal characters, while SHA-256 uses 64. Refs may also be packed or stored by another backend. Use git show-ref to list refs without relying on their on-disk representation.

Staging & State

The staging area bridges your working tree and the object database. When you modify files, Git does not track them automatically — you run git add to snapshot those changes, compute their blob object IDs, and record the mapping in the index, a binary file that serves as the manifest for the next commit. This is what makes partial commits work: you choose which files go into the next snapshot, and only those get committed.

The index also caches information about the current HEAD tree, so Git can instantly determine what has changed without rescanning the entire working directory. When you run git status, Git compares the working tree against the index entries rather than the full object database, which keeps the operation fast even in large repositories.

The index is a structured binary cache, not a simple flag. Each entry records a blob object ID, a file mode (100644 for regular files, 100755 for executables, 040000 for directories), and a stage number (0 for normal entries, higher during merge conflicts). This is what lets git add -p stage individual hunks, and what powers three-way merge during conflict resolution.

The index File

The index (or staging area) is a binary file that tracks which files are staged for the next commit. You can’t read it directly, but you can inspect it:


$ git ls-files --stage
100644 abc123... 0 src/main.py
100644 def456... 0 src/utils.py

Extensibility & Recovery

The hooks/ Directory

Executable scripts that run at specific points in Git’s workflow:


hooks/
├── pre-commit.sample
├── pre-push.sample
├── commit-msg.sample
└── ...

Remove .sample and make executable to activate. Hooks are not versioned — each developer manages their own.

The logs/ Directory

Reflogs track reference movements, enabling recovery of “lost” commits:


$ cat .git/logs/HEAD
0000000... abc123... User <user@email.com> 1711900000 +0000 commit: Initial commit
abc123... def456... User <user@email.com> 1711900100 +0000 commit: Add feature

Other Files

  • description: Repository description (used by GitWeb)
  • packed-refs: Packed references for performance (see Git Object Database and Pack Files)
  • COMMIT_EDITMSG: Last commit message (used by git commit --amend)
  • MERGE_HEAD, REBASE_HEAD: Temporary files during merge/rebase operations

Production Failure Scenarios

Scenario Symptoms Mitigation
Corrupted HEAD “fatal: bad HEAD” Restore from refs/heads/ or use git symbolic-ref HEAD refs/heads/main
Missing objects “fatal: loose object corrupt” Run git fsck --full, fetch from remote, or restore from backup
Broken refs Branch points to non-existent commit Check reflog, reset to valid commit
Lock file stuck “fatal: Unable to create .git/index.lock” Remove stale .git/index.lock after verifying no other Git process runs
Hook failure Commit/push silently fails Check hook exit codes, run hooks manually with bash .git/hooks/pre-commit

Trade-off Analysis

Aspect Advantage Disadvantage
File-based storage Human-inspectable, easy to backup Not optimized for large repos without packing
Object IDs Content addressing and integrity The repository format determines the hash algorithm and ID length
Local hooks Per-developer customization Not shared across team, easy to forget
Reflog Recovery safety net Consumes disk space over time

Implementation Snippets


# Initialize a new repository
git init
ls -la .git/

# Inspect HEAD
cat .git/HEAD

# List all objects with sizes
git count-objects -vH

# View packed refs
cat .git/packed-refs

# Inspect the index
git ls-files --stage

# List hooks
ls -la .git/hooks/

# View reflog
git reflog
cat .git/logs/HEAD

# Create a custom pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
echo "Running pre-commit checks..."
npm run lint
EOF
chmod +x .git/hooks/pre-commit

Observability Checklist

  • Monitor: Repository size growth with git count-objects -vH
  • Log: Hook execution results (hooks should log to stderr)
  • Alert: Reflog size exceeding thresholds (prune with git reflog expire)
  • Verify: Run git fsck --full periodically on critical repositories
  • Track: Number of loose objects vs packed objects

Security & Compliance Considerations

  • The .git directory contains all history — never expose it on a web server
  • Hooks run with the same permissions as the user — validate hook sources
  • Configuration may contain credentials — never commit .git/config with secrets
  • Consider using git config core.hooksPath for shared, versioned hooks

Common Pitfalls / Anti-Patterns

  • Editing .git files directly — always use Git commands unless you know exactly what you’re doing
  • Deleting .git to “reset” — you lose all history; use git reset --hard instead
  • Ignoring hook exit codes — a failing hook should abort the operation
  • Not backing up .git — it IS your repository; the working tree is disposable
  • Sharing hooks via .git/hooks/ — hooks aren’t versioned; use core.hooksPath or a tool like Husky

Quick Recap Checklist

  • .git contains everything Git needs — working tree is disposable
  • HEAD points to current branch or commit
  • objects/ stores content-addressed blobs, trees, commits, and tags under object IDs
  • refs/ contains branch and tag pointers
  • index is the staging area (binary format)
  • hooks/ runs scripts at key Git lifecycle events
  • logs/ enables recovery through reflogs
  • Never expose .git on production web servers

.git Directory Tree


graph TD
    ROOT[".git/"] --> HEAD["HEAD"]
    ROOT --> CONFIG["config"]
    ROOT --> OBJECTS["objects/"]
    ROOT --> REFS["refs/"]
    ROOT --> HOOKS["hooks/"]
    ROOT --> INDEX["index"]
    ROOT --> LOGS["logs/"]
    ROOT --> PACKED["packed-refs"]
    ROOT --> DESC["description"]
    ROOT --> EDITMSG["COMMIT_EDITMSG"]

    OBJECTS --> OBJ_INFO["info/"]
    OBJECTS --> OBJ_PACK["pack/"]
    OBJECTS --> OBJ_LOOSE["<object-ID prefix>/<remaining ID data>"]

    REFS --> REFS_HEADS["heads/ (branches)"]
    REFS --> REFS_TAGS["tags/"]
    REFS --> REFS_REMOTES["remotes/ (tracking)"]

    REFS_HEADS --> RH_MAIN["main"]
    REFS_HEADS --> RH_FEAT["feature/auth"]

    REFS_TAGS --> RT_V1["v1.0.0"]

    REFS_REMOTES --> RR_ORIGIN["origin/"]
    RR_ORIGIN --> RR_MAIN["main"]
    RR_ORIGIN --> RR_DEV["develop"]

Production Failure: Corrupted Repository Recovery

Scenario: Corrupted index file preventing all operations


# Symptoms
$ git status
fatal: .git/index: index file smaller than expected

$ git add .
fatal: Unable to create '/path/to/repo/.git/index.lock': File exists.

# Root cause: Binary index file was truncated or corrupted
# (disk failure, interrupted operation, filesystem corruption)

Do not remove an index lock until you have confirmed that no Git process is using it. Before any repair, save uncommitted work and make a full backup or filesystem snapshot of the working tree and the actual Git/common directory; a `.git` file may point elsewhere.

Start with read-only checks:

```bash
git status
git rev-parse --absolute-git-dir
git rev-parse --git-common-dir
git fsck --full
git count-objects -v

For a damaged index or missing object, use Git’s documented recovery process against a backup. A remote can restore objects it has, but it cannot restore local-only commits. See reflog recovery and object database inspection before attempting repairs.

Manual Object Inspection with Plumbing Commands


# Create a blob and inspect it
echo "Hello, Git internals!" | git hash-object -w --stdin
# Output: 8c7e5a3b2d1f4e6a9c0b8d7e5f3a1c2b4d6e8f0a

# Verify the object exists
git cat-file -t 8c7e5a3b2d1f4e6a9c0b8d7e5f3a1c2b4d6e8f0a
# Output: blob

# Read the blob content
git cat-file -p 8c7e5a3b2d1f4e6a9c0b8d7e5f3a1c2b4d6e8f0a
# Output: Hello, Git internals!

# Check object size
git cat-file -s 8c7e5a3b2d1f4e6a9c0b8d7e5f3a1c2b4d6e8f0a
# Output: 22

# Hash a file without storing it
git hash-object src/main.py
# Output: computes SHA-1 without -w flag

# Inspect a tree object
git cat-file -p HEAD^{tree}
# Output:
# 100644 blob abc123... README.md
# 040000 tree def456... src/
# 100644 blob 789ghi... package.json

# Inspect a commit object
git cat-file -p HEAD
# Output:
# tree 4b825d...
# parent a1b2c3...
# author Name <email> timestamp timezone
# committer Name <email> timestamp timezone
#
# Commit message here

Security: .git Directory Exposure on Web Servers

Exposing .git/ on a production web server is one of the most common and dangerous misconfigurations. Attackers can download your entire source code history, including:

  • All source code — every version of every file ever committed
  • Committed secrets — API keys, passwords, tokens in old commits
  • Developer information — names, emails from commit metadata
  • Infrastructure details — deployment configs, internal URLs

# Check if your site exposes .git
curl -I https://yoursite.com/.git/HEAD
# If you get 200 OK instead of 403/404, you are vulnerable

# Common attack tools that exploit this:
# - git-dumper (downloads entire repo)
# - diggit.py (reconstructs repo from exposed objects)

Mitigation:

  • Nginx: location ~ /\.git { deny all; return 404; }
  • Apache: RedirectMatch 404 /\.git
  • Never deploy .git/ — use build artifacts, not raw repos
  • Scan with: gitleaks detect --log-opts="--all" before deployment

Git Object Types Deep Dive

Git’s object model has four core object types, each serving a distinct purpose in the content-addressable storage system.

Blob

A blob stores file content. It contains only the raw bytes of a file, with no metadata about filename or path. Two files with identical content at different paths share one blob object.


# Blob structure: just content, no metadata
echo "Hello World" | git hash-object -w --stdin
# Creates blob object with no reference to filename

Tree

A tree object references blobs and other trees by object ID, along with file modes and names. Trees represent a directory state at a point in time.


# Inspect tree from commit
git cat-file -p HEAD^{tree}
# 100644 blob a1b2c3... README.md
# 040000 tree d4e5f6... src/
# 100644 blob 789abc... package.json

Commit

A commit object points to a tree (root directory), zero or more parent commits, and contains author/committer metadata with timestamps. Commits form the history graph of your project.


# Commit structure breakdown
git cat-file -p HEAD
# tree 4b825d...                    <- root tree object ID
# parent a1b2c3...                  <- previous commit
# author Geek Workbench <email> timestamp timezone  <- author info
# committer Geek Workbench <email> timestamp timezone <- committer info
#                                         <- blank line
# Commit message here               <- message

Tag

An annotated tag object points to a commit (or another tag) with additional metadata: tagger info, timestamp, and a message. Lightweight tags are just refs; annotated tags are full objects.


# Annotated tag structure
git cat-file -p refs/tags/v1.0.0
# object 4b825d...                  <- pointed commit
# type commit
# tag v1.0.0
# tagger Geek Workbench <email> timestamp
#
# Release version 1.0.0

Object Type Comparison

Aspect Blob Tree Commit Tag (annotated)
Stores File content Directory entries Project snapshot Pointer + metadata
References None Blob and tree object IDs Tree and parent object IDs Commit or tag object IDs
Has author? No No Yes Yes
Has message? No No Yes Yes
Content address File content Directory structure Tree + history Labeled pointer
Typical size Same as file Proportional to files Small (~50-200 bytes) Small (~150-250 bytes)

Interview Questions

1. What is the difference between HEAD and a branch reference in Git?

HEAD is a symbolic reference that points to the current branch (e.g., ref: refs/heads/main). A branch reference is a file in .git/refs/heads/ that points to a specific commit object ID. HEAD moves when you check out different branches; branch refs move when you make new commits.

2. Why does Git use a two-level directory structure for objects (e.g., .git/objects/ab/cdef...)?

In the loose-object layout, Git uses the first byte of an object ID as a directory prefix. The remaining ID characters form the filename; the length depends on the repository's hash format. Packed objects use a different layout.

3. How can you recover a commit that was lost after a hard reset?

Use git reflog to find the object ID of the lost commit. The reflog in .git/logs/HEAD records every HEAD movement, including resets. Once you have the object ID, run git checkout <object-id> or git branch recovery <object-id> to restore it. This works as long as git gc hasn't pruned the unreachable objects.

4. What happens when you run `git add` in terms of the .git directory?

Git creates blob objects in .git/objects/ for each file's content (if not already present), then updates the .git/index binary file to record the blob object ID, file path, and metadata. The working tree files are hashed and compared to existing objects — unchanged files reuse existing blobs, enabling deduplication.

5. Explain the difference between a loose object and a packed object in Git.

In the loose-object layout, compressed objects live under the repository's object directory in a path built from a short object-ID prefix and the remaining ID characters; the ID length depends on the hash format. Packed objects live in pack files with index data. Git maintenance may consolidate loose objects, and the amount of storage saved depends on the repository's content and pack settings.

6. How does the index file enable fast commits?

The index (.git/index) is a binary structure that caches information about the working tree relative to the current HEAD tree. It stores pathnames, blob object IDs, and file stage information. By maintaining this cache, Git avoids rescanning the entire working tree on every commit — it only needs to compare modified files against the cached entries. This enables O(changed_files) commits instead of O(total_files).

7. What is the purpose of the reflog, and how long is data retained?

The reflog records every change to HEAD and branch references in .git/logs/, including timestamp, old and new object IDs, and committer identity. By default, reflogs are retained for 90 days for reachable commits and 30 days for unreachable commits (before garbage collection). They provide a safety net for recovering from destructive operations like git reset --hard or accidentally deleted branches.

8. What happens during `git gc` and why is it important?

git gc (garbage collection) performs several maintenance tasks: it repacks loose objects into pack files using delta compression, removes unreachable objects older than the retention period, rebuilds pack indexes, and prunes stale reflog entries. For active repositories, running git gc periodically keeps object storage efficient and prevents accumulation of orphaned objects.

9. Describe how Git's content-addressable storage ensures data integrity.

Each object is stored or packed under an object ID derived from its type, size, and content using the repository's hash format. When Git reads an object, it checks the computed ID against the stored name; a mismatch indicates corruption. SHA-1 is the default format, while SHA-256 repositories use a different ID length and have interoperability constraints.

10. What is the difference between a symbolic ref and a regular ref in Git?

In the files ref backend, a regular ref (for example, refs/heads/main) stores an object ID that points to a commit. A symbolic ref such as HEAD stores a ref name like ref: refs/heads/main. The object-ID length follows the repository's hash format. Other ref backends, including reftable, do not use this loose-file representation. Use git symbolic-ref and git show-ref rather than editing ref files by hand.

11. How does Git store directory trees in the object model?

Git stores directories as tree objects that map names to blob or tree object IDs and record file modes (100644 for regular files, 040000 for subdirectories). A commit's root tree identifies the project state. Git reuses unchanged blobs and subtrees; changed file bytes get a different blob ID, and updated trees point to the changed entries.

12. Why should `.git` directories never be served by a web server?

Exposing .git/ publicly reveals the entire commit history, all source code (including removed files), all secrets ever committed (even if later removed from history), and developer identity information from commit metadata. Tools like git-dumper can reconstruct entire repositories from exposed .git/ directories. Mitigation: configure web server to deny access to /\.git paths or use build artifacts instead of raw repositories for deployment.

13. What is the difference between `git reset` and `git checkout` in terms of .git internals?

git reset modifies HEAD and/or the index and working tree, updating the current branch ref to point to a different commit. git checkout updates HEAD to point to a different branch (or commit in detached HEAD state), modifies the index to match that commit's tree, and replaces the working tree accordingly. Reset can optionally preserve working tree changes with --soft or --mixed flags; checkout always updates the working tree to match the target.

14. How do custom Git hooks work, and what are the security considerations?

Hooks are executable scripts in .git/hooks/ triggered by Git operations at specific points (pre-commit, post-commit, pre-push, etc.). They are not versioned and not shared via normal clone operations. Security concerns: hooks run with user permissions, can execute arbitrary code, and are a common infection vector for malware. Always validate hook sources, use core.hooksPath to point to a centralized location, or use tools like Husky that manage hooks in the project repository.

15. What is the difference between `git fsck` and `git gc`?

git fsck (file system check) verifies repository integrity by checking object connectivity, dangling object references, and corruption. It reports issues but does not modify anything. git gc performs maintenance operations: repacking, pruning unreachable objects, and reflog cleanup. Use git fsck --full for comprehensive checks; use git gc to reclaim disk space and optimize storage after bulk operations or long periods of active development.

16. Describe the lifecycle of a file from working tree to committed object.

1) git add creates/updates blob in .git/objects/, updates the index with a blob object ID and file metadata. 2) git commit creates a tree object from current index state, creates a commit object pointing to that tree and parent commit(s), then updates the branch ref to point to the new commit. 3) The blob objects persist indefinitely (until gc prunes unreachable ones). The working tree file remains unchanged until checked out from a different commit.

17. How does Git handle file renaming in the object model?

Git does not explicitly track renames — it detects them based on content similarity and object identity. When a file is renamed and staged with git add followed by git mv (or just git add -A), Git stores a new blob with the new name and removes the old blob reference from the tree. The git status and git log --follow commands can trace file history across renames by comparing blob object IDs and content patterns.

18. What is the `packed-refs` file and when does Git use it?

packed-refs is used by the default files ref backend to store many refs in one file; loose refs can coexist with it. A repository using the reftable backend stores refs differently, so this file may not exist. Inspect refs with git show-ref instead of editing storage files directly. See the official repository layout documentation.

19. Explain how the staging area (index) enables partial commits.

The index tracks which version of each file is staged for commit via the blob object ID. You can git add some files, make more changes, then git add again — each git add updates the index with the current blob object ID for that path. When you git commit, only the files recorded in the index are included in the new tree. This enables committing only a subset of changes while keeping other changes unstaged for later commits.

20. What is `REBASE_HEAD` and when does Git create it?

REBASE_HEAD is a temporary file in .git/ created during an interactive or non-interactive rebase. It records the object ID of the commit currently being rebased (the "original" commit before replaying). If a rebase conflicts, REBASE_HEAD indicates which commit you were processing. Similar temporary files include MERGE_HEAD (during merges), CHERRY_PICK_HEAD (during cherry-picks), and BISECT_LOG (during bisect operations).

Further Reading

Conclusion

Use Git commands to inspect repository metadata, and treat filesystem diagrams as examples of a particular layout. For recovery, preserve a backup first and follow the guide for the failure you found.

Category

Related Posts

Centralized vs Distributed VCS: Team Trade-offs

Compare centralized and distributed version control by offline work, repository size, access control, branching, review, and migration effort.

#git #version-control #svn

Automated Changelog Generation

Generate release notes from structured commits, choose a release policy, and add changelog generation to CI without treating every merge as a release.

#git #version-control #changelog

Choosing a Git Team Workflow

Compare trunk-based development, short-lived feature branches, and release branches against your release, review, rollback, and compliance needs.

#git #version-control #branching-strategy