git
submodules
SHA1
commit
version control

Where does Git store the SHA1 of the commit for a submodule?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Git is a highly versatile version control system that not only manages individual repositories but also allows for the inclusion and tracking of external repositories within a parent project through a feature called "submodules." When working with submodules, one important aspect to understand is how Git stores the SHA-1 of the commit specific to each submodule. This article dives into this topic, providing technical explanations and examples to clarify how Git handles submodules.

Understanding Git Submodules

A Git submodule allows you to include and track a separate Git repository within a main repository. It's beneficial for managing dependencies or modular projects. Submodules are pinned to a specific commit SHA-1 in the submodule’s repository, ensuring that the exact same version is checked out each time someone clones the repository containing the submodule.

How Git Tracks Submodule SHA-1

When you add a submodule to a Git repository, the main repository doesn't copy files from the submodule into its history. Instead, it stores only the commit SHA-1 that it should checkout for the submodule. This is captured in a few specific places within the main repository's structure, which are:

  1. `.gitmodules` File:
    This file records metadata about each submodule, such as its path and URL. It doesn't store the SHA-1 directly but provides information about where the submodule is located and how it should be cloned.
  2. Git Index:
    The Git index records the SHA-1 of the submodule at the time of the commit. When you run `git diff`, the index is compared to the working directory to determine changes. If the index indicates a different submodule SHA-1 than what's checked out, Git recognizes this as a modification.
  3. Commit Object:
    Within a commit object that includes changes to submodules, Git stores the SHA-1 of the current commit of the submodule that should be used. This means if you checkout this commit in the future, Git knows exactly which submodule commit to checkout alongside it.
  4. Git Directory (Within the Submodule):
    Each submodule has its own `.git` directory, where information specific to the submodule’s history is kept. However, it's important to note this is separate from how the main repository tracks submodule SHAs.

Example: Viewing Submodule SHA-1

To view the SHA-1 of the commit for a specific submodule, you can use the following command within the main repository:

  • Cloning with Submodules:
  • Updating Submodules:
  • Detached HEAD State:

Course illustration
Course illustration

All Rights Reserved.