Saturday, January 6, 2024

Git: Adding a Submodule to a Repo

Adding a Submodule

I was tasked with adding Opkg utilties to an existing git repo so these utilities could be invoke as part of the build pipeline. The Opkg project is found at:

The logical way to add the contents of a Opkg to to an exising git repo is byusing a git submodule. A submodule can be added to a repo by navigating to the folder in which the local repo resides: 

cd my-repo-folder


From inside the local repo's folder invoke:

git submodule add https://github.com/shr-project/opkg-utils


The command above creates a clone of the repo in folder opkg-utils and creates a .gitmodules file at the local repo's root. The .gitmodules file create is as follows:

[submodule "opkg-utils"]
        path = opkg-utils
        url = https://github.com/shr-project/opkg-utils


The following command shows the current changes related to any submodules:

git diff --cached --submodule


The output from the above code is as follows:

diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..8205de2
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "opkg-utils"]
+       path = opkg-utils
+       url = https://github.com/shr-project/opkg-utils
Submodule opkg-utils 0000000...1f5c57b (new submodule)


The  value 1f5c57b above corresponds to the SHA code of the latest commit the the opkg-utils repo:

1f5c57bfc8c08926a349c395e0e72058f857448e

To perform a git add and git commit for the local repo, the following is invoked

git commit -am 'Task-123: Add Opkg as submodule'

The output from the above add/commit as follows:
 
warning: in the working copy of '.gitmodules', LF will be replaced by CRLF the next time Git touches it
[master 91e677e] Task-123: Add Opkg as submodule
 2 files changed, 4 insertions(+)
 create mode 100644 .gitmodules
 create mode 160000 opkg-utils

The mode, 160000, indicates opkg-utils is a submodule meaning in the repo, opkg-utils is a directory and not a sub directory.

The submodule can be committed to origin (the remote git repo) using the following command:

git push origin master

Note above that the branch name is master. It simply that I signed up for Azure DevOps over a decade above before there was a main branch and before it was called ADO.

In Azure DevOPs the opkg-utils folder looks as follows:


The SHA of the opkg-utils commit is contained in the opkg-util folder meaning the .submodules file is not where the SHA code is stored.

Cloning to Include the Submodule

To clone a repo add the --recurse-submodules parameter tot he standard git clone for the repo:
 
git clone --recurse-submodules https://<repo url here>

Forgetting to Clone with --recurse-submodules

If git clone is performed without --recurse-submodules then see the following to show how to add the the submodule or submodules to an already cloned git repo: Git: Get Submodules from an already Cloned Repo.


No comments :

Post a Comment