Git repo inside a Git repo
To a lot us of picking up git for the first time, sometimes we wonder what if I had a git repo inside another git repo. Alternatively, you may need to include an existing repo into a new project. None the less, I will try to explain how to use git repos inside other git repos.
First off, a git repo inside another is called a submodule. Essentially, submodules are links to the external repos. Also, submodules’ content are ignored when creating a SHA1 out of the working directory’s content. That’s why submodule folders are empty when you first clone a repo with a submodule.
Adding a submodule
To add a submodule all you have to do is use the submodule command:
git submodule add. Let’s play pretend with our examples.
git submodule add git://github.com/jquery/jquery.git git submodule add git://github.com/tpyo/amazon-s3-php-class.git s3-class git add . git commit -m "Added two new submodules."
Adding submodules into your existing repo will create a new file
.gitmoduleswhich contains the directories and URLs to these external repos.
Cloning a Repo with Submodules
Like I mentioned earlier the content inside a submodule is not calculated in your commit’s SHA1s. With this said keep in mind that after cloning a project with submodule, those submodule directories are completely empty. In order to copy down the content of your submodules you need to do a
git submodule init.
git clone email@example.com:mexitek/fake-repo-whatevs.git ...some output about the cloning ... cd fake-repo-whatevs/ git submodule init ... some output on initializing ALL the submodules ... git submodule update ... some output on downloading submodule contents ...
Updating Submodules For Your Parent Repo
Updating submodules is not exactly that straight forward and is more involved. We actually have to tell our parent repo we want to use a new version of a submodule, so a commit is required to acknowledge this change.
cd PATH_TO_SUBMODULE/ git pull origin master # <-- don't forget master!! cd PATH_TO_PARENT_REPO/ git commit -am "Upgrading our Submodules" git push origin
It is important to remember to go to the submodule directory to pull updates for your submodule. Then also to navigate back to the parent repo directory and make your commit. This will tell all other clones of your parent repo that we have upgraded our submodule.
Pulling Submodule Updates From Parent Repo
All other clones of your parent repo will have to execute the following.
git pull origin git submodule update
The initial pull detects a change and pulls a reference down to the latest state of the submodule, then the
git submodule update actually pulls down the new content for the submodule.
Github is your friend
I like how this information is represented in Github.com’s UI. They give you a different icon to represent a submodule, link the name to the original submodule profile and they provide the last commit you have in your repo.