181

In my scripts, I often use libraries (mine or others') that have their own repos. I don't want to duplicate those in my repo and get stuck with updating them every time a new version comes out. However, when somebody clones the repo, it should still work locally and not have broken links.

Any ideas about what I could do?

1 Answer 1

254

You can do this with submodules in git. In your repository, do:

git submodule add path_to_repo path_where_you_want_it

So, if the library's repository had a URL of git://github.com/example/some_lib.git and you wanted it at lib/some_lib in your project, you'd enter:

git submodule add git://github.com/example/some_lib.git lib/some_lib

Note that this needs to be done from the top-level directory in your repository. So don't cd into the directory where you're putting it first.

After you add a submodule, or whenever someone does a fresh checkout of your repository, you'll need to do:

git submodule init
git submodule update

And then all submodules you've added will be checked out at the same revision you have.

When you want to update to a newer version of one of the libraries, cd into the submodule and pull:

cd lib/some_lib
git pull

Then, when you do a git status you should see lib/somelib listed in the modified section. Add that file, commit, and you're up to date. When a collaborator pulls that commit into their repository, they'll see lib/somelib as modified until they run git submodule update again.

11
  • 3
    Thanks for your answer, upvoted! (and will probably accept it tomorrow) Is there a way to add only one file from the other repo as a dependency? Or does it have to be a whole folder?
    – Lea Verou
    Oct 18, 2011 at 23:53
  • 2
    If you want to track it as a submodule (and thus, be able to easily pull in updates) you'll have to pull in the whole repository. Unlike a lot of other VCSs, git really only wants to deal with the top-level repository.
    – Emily
    Oct 19, 2011 at 0:14
  • 10
    read this to know what a submodule is good for and the ways to workaround potential issues. and a discussion about it.
    – minghua
    Jun 11, 2016 at 18:15
  • 4
    I know this is an old answer, but git submodules can be updated using git submodule update --remote I recommend using more flags though for more complex projects. I use git submodule update --remote --recursive --init
    – Chris
    Aug 29, 2017 at 2:33
  • 2
    @topher217 As I understand the answer, you can pick whatever subdirectory you want to put your submodule into, you just call git command from the top level dir (I assume because that's where git configs are).
    – jena
    Apr 19, 2021 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.