How do I "git clone" a repo, including its submodules?
Asked Answered
I

22

2680

How do I clone a git repository so that it also clones its submodules?

Running git clone $REPO_URL merely creates empty submodule directories.

Imitation answered 26/9, 2010 at 7:13 Comment(3)
@LiamCrowley , the parent (hosting, containing) repo might depend on a particular version of the submodule for a variety of reasons. For example, the maintainers of the host repo might not be ready to deal with updates just yet.Strangle
if your repo already exists then you do git submodule init then git submodule update --init potentially with the --remote flag too e.g. https://mcmap.net/q/13651/-how-do-i-quot-git-clone-quot-a-repo-including-its-submodulesPhotomural
for ref, do git clone --recurse-submodules --remote-submodules <repo-URL>Photomural
L
3758

With version 2.13 of Git and later, --recurse-submodules can be used instead of --recursive:

git clone --recurse-submodules -j8 git://github.com/foo/bar.git
cd bar

Editor’s note: -j8 is an optional performance optimization that became available in version 2.8, and fetches up to 8 submodules at a time in parallel — see man git-clone.

With version 1.9 of Git up until version 2.12 (-j flag only available in version 2.8+):

git clone --recursive -j8 git://github.com/foo/bar.git
cd bar

With version 1.6.5 of Git and later, you can use:

git clone --recursive git://github.com/foo/bar.git
cd bar

For already cloned repos, or older Git versions, use:

git clone git://github.com/foo/bar.git
cd bar
git submodule update --init --recursive
Luciennelucier answered 14/12, 2010 at 10:43 Comment(26)
Is there any way to specify this behavior as default in your git repository, so that less-informed cloners will automatically get an initialized submodule?Rafaellle
@Rafaellle Sadly, no. (Not that I know of, at least.)Luciennelucier
And logically thinking git clone --recursive will also populate any submodules of a submodule, right?Fireman
@Rafaellle it seems not: stackoverflow.com/questions/4251940/…Arlenaarlene
you may want to consider git subtree blogs.atlassian.com/2013/05/… It solves the problem in @Rafaellle commentFostoria
@Rafaellle sure, just add this into your ~/.gitconfig under the [alias] section: cloner = clone --recursiveUnspoiled
@Unspoiled While that’s helpful, it doesn’t answer @NHDaly’s question. .gitconfig settings are global, not just for a single repository.Luciennelucier
@mathius-bynens ah you are correct sir. I misread the question.Unspoiled
After doing either of these, it's wise to switch sources to the master branch (or any branch) since your repo will be sort of headless. From the top level repo -- git submodule foreach git checkout masterElconin
@toszter: is it so wise? What if the holding repo needs a version of a submodule that is not master?Hypercriticism
@Hypercriticism - Thank you... if it's any branch other than master, as mentioned, substitute master with your preferred branch name other than master.Elconin
@toszter Even so, the correct commit is not necessarily at the tip of the branch.Hypercriticism
you can use git submodule update --depth 10 --recursive --init to shallow the repoUrbain
This doesn't work with git 2.7, but worked with git 2.9Pizza
Thanks! I had forgotten to actually retrieve the submodule dependency contents with git submodule update --init --recursive before running sh -c 'cd cmd/ios7crypt && go install'Hypocrisy
I did git submodule update --init --recursive but all the submodules are in dechated head state, I have to go into each submodule and checkout master. Does anybody know why?Mcnelly
I have git 1.9.1 and git clone --recursive -j8 [email protected]:repoToClone does not work. It tells me error: unknown switch j' ` If I remove the -j8 it works smoothlyCottrill
As it seems, the flag name was updated to --recurse-submodulesHyperostosis
I think I come back to this answer once a month... Why don't git just ask upon cloning if it should also download the submodules?Hixon
I suppose the -j8 option is not available for already clone repos?Eloign
If the repos is not public and a token/authentication is needed, this cmd will ask you to type in again and again the access token/ or user_password for every submodule. Is there any workaround?Ashleaashlee
Also to make clear (since I wanted to know and couldn't find an answer except by looking at the source), the git clone --recursive and --recurse-submodules options behave identically. They result in a call to the same function.Columbary
Why isn't recursive cloning the default option?Bless
what happens if you do them in reverse?Photomural
why is your answer better than git clone --recurse-submodules --remote-submodules <repo-URL>?Photomural
@Ashleaashlee my solution to that is to talk to any remote via ssh and ask git to rewrite such https urls to ssh using the url.xyz.insteadOf config. For my client that uses bitbucket, this looks like the following: git config --global url."[email protected]:".insteadOf "https://bitbucket.org/" If you only want to do it for a specific org: git config --global url."[email protected]:that-org/".insteadOf "https://bitbucket.org/that-org/"Zarate
G
643

You have to do two things before a submodule will be filled:

git submodule init 
git submodule update
Gregale answered 26/9, 2010 at 7:19 Comment(10)
I was afraid of that... it doesn't make any sense since you're checking out a partial project in that case. I understand that the submodule updates aren't automatic, but why isn't the bound version automatically checked out?? Is there any way to force it? I have a project with 3-levels of submodules and it seems absurd to have to traverse that far just to do a checkout.Imitation
Please read the git-submodule(1) man page (kernel.org/pub/software/scm/git/docs/git-submodule.html). You'll find out that git submodule update supports a nice parameter called --recursive.Photography
Why not just do both of them in one command? git submodule update --init (Also see my answer).Luciennelucier
I think its better to answer the question with these two commands. Its explains better how to accomplish the task.Howzell
@MathiasBynens A machine that I just logged into only has git 1.5.5.6, which apparently does not support the shortened instruction, but does support it as two commands.Chalcis
@MathiasBynens I think you misunderstood. git submodule update --init must be expanded to git submodule init; git submodule update in 1.5.5.6.Chalcis
After I do this, then if I cd into the submodule directory and to git pull it says its head is detached and I can't do git pull in it to update, any way to fix this?Tourney
what happens if you do them in reverse?Photomural
why not git submodule update --init --recursiveAndrow
Because when that answer was made (2010) that was not an option.Gregale
J
357

Git 2.23 (Q3 2019): if you want to clone and update the submodules to their latest revision:

git clone --recurse-submodules --remote-submodules <repo-URL>

If you just want to clone them at their recorded SHA1:

git clone --recurse-submodules <repo-URL>

See below.

Note that Git 2.29 (Q4 2020) brings a significant optimization around submodule handling.

See commit a462bee (06 Sep 2020) by Orgad Shaneh (orgads).
(Merged by Junio C Hamano -- gitster -- in commit 2ce9d4e, 18 Sep 2020)

submodule: suppress checking for file name and ref ambiguity for object ids

Signed-off-by: Orgad Shaneh

The argv argument of collect_changed_submodules() contains only object ids (the objects references of all the refs).

Notify setup_revisions() that the input is not filenames by passing assume_dashdash, so it can avoid redundant stat for each ref.

Also suppress refname_ambiguity flag to avoid filesystem lookups for each object. Similar logic can be found in cat-file, pack-objects and more.

This change reduces the time for git fetch(man) in my repo from 25s to 6s.


Original answer 2010

As joschi mentions in the comments, git submodule now supports the --recursive option (Git1.6.5 and more).

If --recursive is specified, this command will recurse into the registered submodules, and update any nested submodules within.

See Working with git submodules recursively for the init part.
See git submodule explained for more.

With version 1.6.5 of git and later, you can do this automatically by cloning the super-project with the –-recursive option:

git clone --recursive git://github.com/mysociety/whatdotheyknow.git

Update 2016, with git 2.8: see "How to speed up / parallelize downloads of git submodules using git clone --recursive?"

You can initiate fetching the submodule using multiple threads, in parallel.
For instances:

git fetch --recurse-submodules -j2

Even better, with Git 2.23 (Q3 2019), you can clone and checkout the submodule to their tracking branch in one command!

See commit 4c69101 (19 May 2019) by Ben Avison (bavison).
(Merged by Junio C Hamano -- gitster -- in commit 9476094, 17 Jun 2019)

clone: add --remote-submodules flag

When using git clone --recurse-submodules there was previously no way to pass a --remote switch to the implicit git submodule update command for any use case where you want the submodules to be checked out on their remote-tracking branch rather than with the SHA-1 recorded in the superproject.

This patch rectifies this situation.
It actually passes --no-fetch to git submodule update as well on the grounds the submodule has only just been cloned, so fetching from the remote again only serves to slow things down.

That means:

--[no-]remote-submodules:

All submodules which are cloned will use the status of the submodule’s remote-tracking branch to update the submodule, rather than the superproject’s recorded SHA-1. Equivalent to passing --remote to git submodule update.


jhu notes in the comments:

If you want to use git clone --recurse-submodules --remote-submodules <repo-URL> to clone and update to the latest version, your submodules must either:

  1. have a branch master, assumed by git when running the above, or
  2. record a valid branch name in the .gitmodules of the cloned repo. > Otherwise you will get an error about a missing head, and cloning will fail.
    So if you have a submodule without branch master, say submodule sub with branch main, run in the root dir of the cloned repo git config -f .gitmodules submodule.sub.branch main and push your changes to the remote.
Jeroboam answered 26/9, 2010 at 8:17 Comment(14)
So it took Git 14 years to start adding proper support for submodules, huh. Thanks for the update! What if I already have a clone of the main repo without submodules and without a recorded SHA1, and I want to pull in the latest version of each submodule. Is it doable?Slurp
@VioletGiraffe If that cloned repository has submodules, it has "recorded SHA1". And a git submodule update --init --recursive --remote should update them to the latest commit of their respective branch. (ex: https://mcmap.net/q/13878/-how-to-fix-git-submodule-update-init-recursive-not-pulling-cmakelists-txt)Jeroboam
Let me clarify with an example: I have a template project on Github that uses submodules, and I even commited specific revisions of the submodules into this template repo. But when I create a new project out of this repo, none of the commands you listed (neither clone --recurse-submodules --remote-submodules nor submodule update --init --recursive --remote) let me actually fetch the subrepos. All I get is a .gitmodules file, and I couldn't find any way to init the subrepos other than manually cloning them one by one. I'd like to at least have a script to do it with submodule foreach...Slurp
If you know a solution, I'd ask a separate question that you could answer. Here's the test repo that I can't find any way to init other than by hand: github.com/VioletGiraffe/TESTSlurp
@VioletGiraffe That is because you have added and committed the .gitmodules but not the gitlink (https://mcmap.net/q/13007/-how-do-i-add-files-in-git-to-the-path-of-a-former-submodule, special entries in the index: https://mcmap.net/q/13008/-egit-in-eclipse-missing-tree) Here is a repository which does have the proper gitlink registered: github.com/tiagomazzutti/antlr4dartJeroboam
@VioletGiraffe Solution: clone your repo, delete the .gitmodules, add, and commit. Then add the submodules again: git submodule add cpputils https://github.com/VioletGiraffe/cpputils.git and git submodule add cpp-template-utils https://github.com/VioletGiraffe/cpp-template-utils. Add, commit and push. You will then see your submodules, and can clone back that repository with said submodules.Jeroboam
Right, I understand that, and it works for any "normal" repo you create from scratch. I think we're looking at a Github bug with regards to handling subrepos in project templates specifically, because the original template repo has gitlinks as well, but not the new project created from this template. P. S. Thanks for the answers!Slurp
@VioletGiraffe You could still update that project template with the process I mentioned. But yes, that looks like a bug on GitHub side. That would be interesting to illustrate/detail that in a separate question. I will answer it when I go back from work.Jeroboam
What exactly does --remote-submodules? Does it pull for each submodule the latest commit, and then update the reference in the superproject?Crittenden
@AvivCohn It does pull for each submodule the latest commit of their associated branch (master/main by default). To my understanding, you still need to add and commit in the parent repo, in order to record the new submodules tree SHA.Jeroboam
isn't your git clone cmd missing the repo url?Photomural
If you want to use git clone --recurse-submodules --remote-submodules <repo-URL> to clone and update to the latest version, your submodules must either 1. have a branch master, assumed by git when running the above, or 2. record a valid branch name in the .gitmodules of the cloned repo. Otherwise you will get an error about a missing head, and cloning will fail. So if you have a submodule without branch master, say submodule sub with branch main, run in the root dir of the cloned repo git config -f .gitmodules submodule.sub.branch main and push your changes to the remote.Straphanger
@Straphanger Good point, thank you for this feedback. I have included your comment in the answer for more visibility.Jeroboam
This answer is the closest one to the question post.Slug
O
170

You can use this command to clone your repo with all the submodules:

git clone --recursive YOUR-GIT-REPO-URL

Or if you have already cloned the project, you can use:

git submodule init
git submodule update
Oddment answered 16/10, 2017 at 15:47 Comment(3)
On git version 2.24.3 the above command gives me the error: error: Server does not allow request for unadvertised object e635630d55682951eb2da35630d5da15b6cc Fetched in submodule path 'ui-library', but it did not contain e635630d55682951eb2da35630d5da15b6cc. Direct fetching of that commit failed.Surreptitious
ran the second option, nothing happensSluggish
what happens if you do them in reverse?Photomural
S
123

[Quick Answer]

After cloning the parent repo (including some submodule repos), do the following:

git submodule update --init --recursive
Statfarad answered 1/7, 2019 at 9:39 Comment(1)
or --remote if you want the right branchPhotomural
L
47

Use this command to clone repo with all submodules

git clone --recurse-submodules [email protected]:yourproject

To update code for all submodules

git submodule update --recursive --remote
Liquorish answered 18/3, 2021 at 12:44 Comment(1)
--remote also makes sure the right branch from remote is used. Right?Photomural
J
40

If your submodule was added in a branch be sure to include it in your clone command...

git clone -b <branch_name> --recursive <remote> <directory>
Jurgen answered 7/3, 2012 at 22:28 Comment(1)
This was more like what I was looking for... but the submodules list their branch as 'detached'. :(Thermomagnetic
M
35

Try this:

git clone --recurse-submodules

It automatically pulls in the submodule data assuming you have already added the submodules to the parent project.

Metagenesis answered 16/1, 2013 at 18:39 Comment(2)
Note that --recurse-submodules and --recursive are equivalent aliases.Chesterton
@SuperUberDuper in that case you can do git submodule update --init --recursive as explained in this answerStandstill
E
28

I think you can go with 3 steps:

git clone
git submodule init
git submodule update
Eleni answered 16/1, 2019 at 14:11 Comment(0)
A
25

You can use the --recursive flag when cloning a repository. This parameter forces git to clone all defined submodules in the repository.

git clone --recursive [email protected]:your_repo.git

After cloning, sometimes submodules branches may be changed, so run this command after it:

git submodule foreach "git checkout master"
Autarch answered 17/1, 2019 at 4:44 Comment(2)
+ 1 foreach but not enough details. see this for a more detailed answer: stackoverflow.com/questions/74988223/…Photomural
The checkout done here switches from a snapshot (detached head) to a working branch. And, say you have some submodules where the branch you want to work with is master, and some submodules where the branch you want to work with is main. (This is quite common now, since master used to be the default, but now it is typically main.) Then you can check out a working branch of all submodules by running git submodule foreach --recursive "git checkout master || git checkout main" Straphanger
T
22

late answer

// git CLONE INCLUDE-SUBMODULES ADDRESS DESTINATION-DIRECTORY
git clone --recursive https://[email protected]/USERNAME/REPO.git DESTINATION_DIR

As I just spent a whole hour fiddling around with a friend: Even if you have Admin rights on BitBucket, always clone the ORIGINAL repository and use the password of the one who owns the repo. Annoying to find out that you ran into this minetrap :P

Tardy answered 16/2, 2013 at 16:10 Comment(9)
That's exactly what I'm dealing with. So, are you saying that anyone who needs to develop on a bitbucket repository that has submodules must use the repository creator's credentials? Blech.Delao
@Delao Seems so - it sucks BIG TIME... and I know it.Tardy
That sounds like a bug. Did you report it to Bitbucket?Luciennelucier
@MathiasBynens Did you stumble upon this issue? It's one and a half years later and I actually don't know if this is still the case.Tardy
@Tardy No, I just stumbled upon your answer and was surprised.Luciennelucier
This is the case only if you use HTTPS and the user is in the URL? The "right" way is to use the SSH auth with a private/public key pair, so the password would not be requested.Bailment
@Tardy This answer should really be deletedSpirituality
It doesn't descriptively answer the OPs question, but details an unrelated bug in Bitbucket; which, incidentally, could just be shortened to "use SSH key authentication".Spirituality
Still not resolved on Bitbucked. I'm using relative paths to submodules and as a trick I have to perform following steps: - git remote set-url origin [email protected]:namespace/main-repo.git - git submodule update --init --recursiveNobell
E
21

Try this for including submodules in git repository.

git clone -b <branch_name> --recursive <remote> <directory>

or

git clone --recurse-submodules
Eolithic answered 5/2, 2018 at 4:54 Comment(0)
S
19

Just do these in your project directory.

$ git submodule init
$ git submodule update
Sutphin answered 8/3, 2021 at 4:54 Comment(1)
This is the right answer if you had already cloned your repo before.Eliathas
P
12

Submodules parallel fetch aims at reducing the time required to fetch a repositories and all of its related submodules by enabling the fetching of multiple repositories at once. This can be accomplished by using the new --jobs option, e.g.:

git fetch --recurse-submodules --jobs=4

According to Git team, this can substantially speed up updating repositories that contain many submodules. When using --recurse-submodules without the new --jobs option, Git will fetch submodules one by one.

Source: http://www.infoq.com/news/2016/03/git28-released

Pundit answered 6/4, 2016 at 12:7 Comment(0)
A
10

If it is a new project simply you can do like this :

$ git clone --recurse-submodules https://github.com/chaconinc/YourProjectName 

If it is already installed than :

$ cd YourProjectName (for the cases you are not at right directory) 
$ git submodule init
$ git submodule update
Acescent answered 26/8, 2019 at 8:46 Comment(0)
A
10

I had the same problem for a GitHub repository. My account was missing SSH Key. The process is

  1. Generate SSH Key
  2. Adding a new SSH key to your GitHub account

Then, you can clone the repository with submodules (git clone --recursive YOUR-GIT-REPO-URL)

or

Run git submodule init and git submodule update to fetch submodules in already cloned repository.

Azarria answered 26/8, 2019 at 20:51 Comment(1)
Yes, that is Permission denied (publickey). fatal: Could not read from remote repository. errorFeuchtwanger
S
8

Try this.

git clone -b <branch_name> --recursive <remote> <directory>

If you have added the submodule in a branch make sure that you add it to the clone command.

Szabadka answered 18/6, 2018 at 8:29 Comment(0)
B
2

If you want to tell your git client to do all actions with --recurse-submodules then you can set this to your git config:

git config submodule.recurse true

See: https://www.git-scm.com/docs/git-config#Documentation/git-config.txt-submodulerecurse

Buhr answered 14/3, 2023 at 8:42 Comment(3)
Unless this is for a newer git than I have, this does not appear to work (even with --global).Postbellum
@Postbellum submodule.recurse is documented in man git config in my git version 2.39.2Eby
Yeah, the documentation that you have linked to says "clone and ls-files are not supported." So, I do not believe that config option works to do this (it works for other things, just not clone).Postbellum
P
1

I recommend:

# - git submodule init initializes your local configuration file to track the submodules your repository uses, it just sets up the configuration so that you can use the git submodule update command to clone and update the submodules.
git submodule init
# - git submodule update --init initializes your local configuration file and clones the submodules for you, using the commit specified in the main repository.
#   note, command bellow will not pull the right branch -- even if it's in your .gitmodules file, for that you need remote. Likely because it looks at the origin (pointer to remote) in github for the available branches.
#   note, bellow pulls the submodules if you didn't specify them when cloning parent project, ref: https://youtu.be/wTGIDDg0tK8?t=119
git submodule update --init

if you have a specific branch for your submodules then change it to:

# - git submodule init initializes your local configuration file to track the submodules your repository uses, it just sets up the configuration so that you can use the git submodule update command to clone and update the submodules.
git submodule init

# - The --remote option tells Git to update the submodule to the commit specified in the upstream repository, rather than the commit specified in the main repository.
#git submodule update --init --remote
git submodule update --init --recursive --remote meta-dataset

For a full example that was testing:

# decided against this because it seems complicated

# - note to clone uutils with its submodule do (cmd not tested):
cd $HOME
git clone --recurse-submodules [email protected]:brando90/ultimate-utils.git

# - git submodules
cd $HOME/diversity-for-predictive-success-of-meta-learning

# - in case it's needed if the submodules bellow have branches your local project doesn't know about from the submodules upstream
git fetch

# -- first repo
# - adds the repo to the .gitmodule & clones the repo
git submodule add -f -b hdb --name meta-dataset [email protected]:brando90/meta-dataset.git meta-dataset/

# - ref for init then update: https://mcmap.net/q/13651/-how-do-i-quot-git-clone-quot-a-repo-including-its-submodules/3796947#3796947
#git submodule init
#git submodule update

# - git submodule init initializes your local configuration file to track the submodules your repository uses, it just sets up the configuration so that you can use the git submodule update command to clone and update the submodules.
git submodule init
# - git submodule update --init initializes your local configuration file and clones the submodules for you, using the commit specified in the main repository.
#   note, command bellow will not pull the right branch -- even if it's in your .gitmodules file, for that you need remote. Likely because it looks at the origin (pointer to remote) in github for the available branches.
#   note, bellow pulls the submodules if you didn't specify them when cloning parent project, ref: https://youtu.be/wTGIDDg0tK8?t=119
git submodule update --init
# - The --remote option tells Git to update the submodule to the commit specified in the upstream repository, rather than the commit specified in the main repository.
#git submodule update --init --remote
git submodule update --init --recursive --remote meta-dataset

# - check we are using the right branch https://mcmap.net/q/13650/-why-does-git-submodule-status-not-match-the-output-of-git-branch-of-my-submodule
git submodule status
cd meta-dataset
git branch  # should show hdb
cd ..

# pip install -r $HOME/meta-dataset/requirements.txt

# -- 2nd repo, simplified commands from above
git submodule add -f -b hdb --name pytorch-meta-dataset [email protected]:brando90/pytorch-meta-dataset.git pytorch-meta-dataset/

git submodule init
git submodule update --init --recursive --remote meta-dataset

# - check it's in specified branch
git submodule status
cd pytorch-meta-dataset
git branch  # should show hdb
cd ..

# pip install -r $HOME/pytorch-meta-dataset/requirements.txt
Photomural answered 26/9, 2010 at 7:13 Comment(0)
S
1
git submodule init
git submodule update

or maybe:

git stash -u
git pull origin master
git stash p
Sharpeyed answered 13/4, 2022 at 15:51 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Fai
I
0

If the submodules are private submodules you can use credential store so that it also clones its private submodules recursively.

USER=${GITHUB_ACTOR}
TOKEN=${{ secrets.JEKYLL_GITHUB_TOKEN }}

git config --global credential.helper store
echo "https://${USER}:${TOKEN}@github.com" > ~/.git-credentials

git clone --recurse-submodules -j8 git://github.com/foo/bar.git
cd bar

I use it to clone my submodules where the private one is in 5th level deep. Please allow me to show you how it goes in action:

enter image description here

Inflight answered 6/11, 2022 at 19:17 Comment(0)
D
0

You can copy clone url from github.

Then use:

git clone --recursive <url of clone copied above>
Devora answered 16/1, 2023 at 13:59 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Fai

© 2022 - 2024 — McMap. All rights reserved.