ripper234
ripper234

Reputation: 230028

How to change a git submodule to point to a subfolder?

Skimming through the SubModule tutorial, I created a submodule out of the boto project. Then, I discovered that I actually need only a subset of this project - specifically, the boto folder.

I would like to change my submodule to point to this folder. When I look in .gitmodules, I see

[submodule "backup/src/boto"]
    path = backup/src/boto
    url = https://github.com/boto/boto.git

What URL should I use instead of https://github.com/boto/boto.git? After I change the URL, should I delete the boto folder locally and re-pull?

Upvotes: 152

Views: 109235

Answers (5)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

Save the submodule to the submodules/ directory, and then create a symlink:

git submodule add https://github.com/user/repo submodules/repo
ln -s submodules/repo/subdir .
git add subdir

Result:

./
  submodules/
    repo/
      subdir/

  subdir  -->  ./submodules/repo/subdir

One benefit to this approach is that it can be reused with multiple subdirectories.

Upvotes: 12

Justin Hammond
Justin Hammond

Reputation: 719

All the answers here are pretty dated. You could use the newer git sparse-checkout command docs here, further examples in this article to grab pieces of a repo. This is effective if you only want a directory or two from a larger git project.

TLDR:

git sparse-checkout init --cone
git sparse-checkout set <dir1> <dir2> ...
git checkout main

Upvotes: 26

Mark Longair
Mark Longair

Reputation: 467161

I'm afraid the URL for submodules always just points to the repository - you can't specify that you only want a subfolder of a repository, in the same way that git doesn't support "narrow clones" in general.

If you can't live with having the whole repository as a submodule, you could always create a new repository that's cloned from boto and then set up a cron job to:

  1. git fetch that repository into a directory
  2. Use git filter-branch to update a branch where the subdirectory is at the top level.
  3. Add that branch of the repository as the submodule. However, that's all a bit fiddly and my preference would just be to live with having the whole repository as a submodule.

Upvotes: 88

Adam Dymitruk
Adam Dymitruk

Reputation: 129556

What you want to do is create a branch in the submodule and move the folder up and delete what you don't need. You can then manage that branch instead. If you want to push up your changes, you should be able to back merge first. Git will know that you moved the files and do the merge successfully.

Hope this helps.

Upvotes: 18

Artefact2
Artefact2

Reputation: 7634

You cannot clone only a part of a repository. This is because git treats the repository as a whole object : when you get it, you get it all.

So, the solution here would be to fetch the submodule in another directory, then use a symlink to achieve your goal.

Upvotes: 36

Related Questions