Skip to content

Instantly share code, notes, and snippets.

@amomin
Last active July 11, 2024 14:39
Show Gist options
  • Save amomin/b0df11ac4607f15203ac to your computer and use it in GitHub Desktop.
Save amomin/b0df11ac4607f15203ac to your computer and use it in GitHub Desktop.
Converting a folder into a git submodule

Essentially following this answer:

https://stackoverflow.com/questions/12514197/convert-a-git-folder-to-a-submodule-retrospectively

Looking at the docs for git filter-branch is useful too:

Creating the submodule

First, create a cloned copy of your directory

git clone working-dir/.git working-dir-copy
cd working-dir-copy

At this point you should have a full copy. We will apply git filter-branch to retain only a specific subdirectory (let's call it path/to/subdir)

git filter-branch --subdirectory-filter 'path/to/subdir' --prune-empty -- --all

You should now see that the new project contents contain that subfolder, and only commits affecting the subfolder appear in the history.

Filtering the submodule out of the original repo

In case you want it to appear as though the subdirectory never appeared in the repo in the first place:

Create a second clone (just to be safe so we have a copy of the original):

git clone working-dir/.git working-dir-copy
cd working-dir-copy2

From the filter-branch documentation, use --index-filter with git -rm to remove the subdirectory.

git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch path/to/subdir' HEAD

This removes the subdirectory completely from the working directory and the history.

@Mike-Jagger
Copy link

Great resource here

Small typo though in the Filtering the submodule out of the original repo section:

Create a second clone (just to be safe so we have a copy of the original):

- git clone working-dir/.git working-dir-copy
+ git clone working-dir/.git working-dir-copy2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment