DEV Community

loading...
Cover image for Submodule - link to another Git repository

Submodule - link to another Git repository

teresac01 profile image Teresa Carbajal ・2 min read

"A common issue arises in these scenarios: you want to be able to treat the two projects as separate yet still be able to use one from within the other.

Git addresses this issue using submodules. Submodules allow you to keep a Git repository as a subdirectory of another Git repository. This lets you clone another repository into your project and keep your commits separate."

🤓 Git documentation: https://www.git-scm.com/book/en/v2/Git-Tools-Submodules

Before Repo -- without running the commands below

Alt Text

Command with the URL of the project you would like to start tracking.

👇

// Enter local computer project
$ cd ~/projects/name-project

// Add submodule
$ git submodule add <URL GitHub project>

// Add commit
$ git commit -am 'Add submodule'
Enter fullscreen mode Exit fullscreen mode
  • Sometimes we can need the next command if you used checkout to change other branches:
// Update submodule if you used checkout command
$ git submodule update --init --recursive
Enter fullscreen mode Exit fullscreen mode

After Repo -- if you run the above commands

Alt Text

Alt Text

OTHER OPTION: You would like to start tracking in a new branch.

👇

// For creating a new branch use command:
$ git checkout -b add-branch-submodule

// Add submodule
$ git submodule add <URL GitHub project>

// Add commit
$ git commit -am 'Add submodule'

// Switched to branch 'master'
$ git checkout --recurse-submodules master

// Check status
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

// after the checkout, you can use:
$ git submodule update --init --recursive
Enter fullscreen mode Exit fullscreen mode


"If you haven’t committed your changes in your submodule and you run a submodule update that would cause issues, Git will fetch the changes but not overwrite unsaved work in your submodule directory."

$ git submodule update --remote
Enter fullscreen mode Exit fullscreen mode


Some recourses:

Discussion (0)

pic
Editor guide