How to quickly carve out a subdirectory from git and use it as a git submodule?

git submodule structure
  • Make sure that you’re at the root folder of your master branch (or however your git repository’s main branch is called) and temporarily remove all files from the git working tree with the git command below. It is important to pass the --cached-flag to your git CLI command. The --cached flag is crucial because it tells git to only remove the files from its working tree and to not actually delete them.
~$ git rm -rf --cached ./
  • Remain on the master branch and move files and folders around so that the source code sits at the root of the git repository. The file structure should now resemble the target file structure for your submodule, but once again, DO NOT DELETE ANY FILES!
  • Add ONLY THE SOURCE CODE FILES back to the git working tree with the following git command:
~$ git add <filename>
  • Now, with all the files moved around and added back to the git working tree, checkout a new branch off of the master branch (I’ll refer to this new branch as the “submodule” branch going forward)
~$ git checkout -b submodule
  • Right after having checked out the submodule branch, switch back to the master branch, move all files into their original location, add ALL files back to the git working tree and commit your changes to the master branch.
~$ git checkout master & git add -A & git commit -m “<your commit message>”
git submodule add -b submodule <git-repository-URI>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store