Understanding Git Commit Contents
Git is a powerful version control system, and a frequent task is examining the changes introduced by specific commits. Often, you’ll need to simply list the files that were modified, added, or deleted within a particular commit, without seeing the detailed diffs. This tutorial will cover several ways to accomplish this using Git commands.
Basic Listing with git show
The git show
command is designed to display various types of Git objects, including commits. By default, it shows the commit message, author, date, and the detailed changes (diffs). However, you can tailor its output to display only the file names.
git show --name-only <commit-hash>
Replace <commit-hash>
with the SHA-1 hash of the commit you’re interested in. The --name-only
flag instructs Git to print only the names of the files that were changed in that commit. This is a simple and direct approach for quick inspection.
Using git diff-tree
for More Control
The git diff-tree
command is a more flexible way to explore commit contents. It’s designed as a "plumbing" command—meaning it’s intended for scripting and programmatic use—giving you fine-grained control over the output.
git diff-tree --no-commit-id --name-only -r <commit-hash>
Let’s break down the flags:
--no-commit-id
: Suppresses the display of the commit ID.--name-only
: As withgit show
, this flag displays only the file names.-r
: This crucial flag enables recursive traversal of the commit tree. Without it, the command will only list files directly modified in the top-level directory of the commit and won’t descend into subdirectories.
git diff-tree
is particularly useful when you need to process the list of files programmatically in a script.
Exploring All Files in a Commit with git ls-tree
Sometimes you need to know all the files present in a commit, not just those that were changed. The git ls-tree
command is designed for this purpose.
git ls-tree --name-only -r <commit-hash>
The --name-only
and -r
flags function identically to those used with git diff-tree
. This command lists every file and directory contained within the specified commit, giving you a complete snapshot of the project’s structure at that point in time.
Viewing File Changes Across Multiple Commits
You can also use these commands to view file changes across a range of commits. For example:
git diff-tree --no-commit-id --name-only -r HEAD^^..HEAD
This command displays the files changed between the commit two commits before HEAD
and the current HEAD
commit. The ^^
notation represents "two commits before HEAD".
Choosing the Right Command
- For a quick list of changed files in a single commit,
git show --name-only <commit-hash>
is the simplest option. - For more control and scripting purposes, or when dealing with complex commit histories,
git diff-tree
is the preferred choice. - If you need a complete list of all files within a commit,
git ls-tree
is the tool for the job.