Sub topic 1
Plumbing and Porcelain: Two Layers of Git Commands
Prerequisites
Assume you know git init, git add, git commit, and git log. You should also be comfortable running commands in a Unix-style shell and know that a hash is a fixed-length value derived from data.
Plumbing and porcelain
Git has two command layers:
- Porcelain commands are the user-friendly commands used for normal work, such as
git add,git commit, andgit switch. - Plumbing commands are lower-level commands that expose Git's internal storage, such as
git hash-object,git cat-file, andgit update-ref.
Porcelain is convenient. Plumbing is useful when you need to understand, inspect, script, or repair Git's data model.
A tour of the `.git` directory
After git init, the repository's working files are separate from its .git directory. The .git directory contains Git's private metadata.
| Path | Purpose |
|---|---|
| `.git/objects` | Stores Git objects |
| `.git/refs` | Stores branch and tag names |
| `.git/HEAD` | Records the current branch or commit |
| `.git/index` | Stores the staging area |
Other files, such as config, hold repository settings. The exact layout can vary slightly by Git version and repository state.
Git as a content-addressable object store
Git stores data as objects and names each object by an object ID, normally a SHA-1 hash. The ID depends on both the object's type and its contents. The same data therefore produces the same ID in any repository using the same hash format.
Git mainly uses four object types:
- A blob stores file contents.
- A tree stores names, modes, and references to blobs or other trees.
- A commit stores a snapshot reference, metadata, and parent commits.
- A tag stores metadata about another object.
Writing objects with `git hash-object`
This command writes text as a blob and prints its object ID:
mkdir plumbing-demo
cd plumbing-demo
git init
id=$(printf 'hello\n' | git hash-object -w --stdin)
printf '%s\n' "$id"The -w option writes the object. Without it, Git only calculates the ID.
> callout note > Object IDs identify stored content. A filename is not part of a blob, so renaming a file does not change its blob when its contents stay the same.
Reading objects with `git cat-file`
Use git cat-file to inspect an object:
git cat-file -t "$id"
git cat-file -s "$id"
git cat-file -p "$id"These commands print the type, size, and contents. The -p option chooses a readable representation for the object's type.
Exercise
Which command writes stdin as a Git blob, and which command prints that blob's contents?
Show answer
git hash-object -w --stdin writes it, and git cat-file -p OBJECT_ID prints it.