Monday 20 October 2014

Git Submodules

This blog post is a very simple description on how to use a very important feature of GIT i.e submodules.

Requirement:
How to use a third party library into your app without keeping the source code for library project inside your repository ?There are multiple ways to include a third party code into your app. Either copy the entire source code into your app or get it installed using some tool like Ruby gem or CPAN install.

Or else you could import the remote third party repository into your code without getting its actual code by using git submodule feature. This is also used to include a third party repository without making your own repository getting heavier in size.
This approach also allows you to contribute back to the third party repository.


Submodules:
Submodules allow you to keep a Git repository as a sub-directory of another Git repository. This lets you clone another repository into your project and keep your commits separate.

 What you need to get the library :
Add the external repository under your project in a sub-directory. You can do this by the calling following git command from the project's repository


        git submodule add <remote url> <subdirectory name>  
        example :
        git submodule add https://github.com/couchbase/couchbase-lite-android.git  mylibs

Now you will have the library project under subdirectory folder. and will see that you have a new file in your project directory
        new file:   .gitmodules
        new file:  <subdirectory name> (in example mylibs which will contain the external lib project)
 

   
.gitmodules is a configuration file that contains the mapping between the library project's url and the subdirectory to which it is pulled into. 



What git thinks of and does with submodules :
Although <subdirectory name> is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git records it as a particular commit from that repository.
When you make changes and commit in that subdirectory, the superproject notices that the HEAD there has changed and records the exact commit you’re currently working off of; that way, when others clone this project, they can re-create the environment exactly.

All the Git commands work independently in the two directories.



What other users need to do to get your repository along with submodules : 
1. Clone the repository.
       $ git clone <repository_url>
2. Navigate to root of the project directory

       $ cd <repo_name>
2. call following command from project's root

       $ git submodule init && git submodule update
      
You must run above two commands: git submodule init to initialize your local configuration file, and git submodule update to fetch all the data from that project.


Now you are ready to Clean, Build and Run.


No comments:

Post a Comment