Skip to content

Instantly share code, notes, and snippets.

@sdumitriu
Created March 7, 2012 14:13
Show Gist options
  • Save sdumitriu/1993357 to your computer and use it in GitHub Desktop.
Save sdumitriu/1993357 to your computer and use it in GitHub Desktop.
How to extract a submodule from a git repository, taking into consideration subdirectory moves (an advanced filter-branch --subdirectory-filter)
#!/bin/bash
echo Cloning repository...
git clone git@github.com:organization/project.git
cd project
echo
echo Removing origin
git remote rm origin
echo
echo Filtering the history
# Modify this line
git filter-branch --prune-empty --index-filter 'git ls-files -s | sed -r -f /path/to/keep-module.sed | git update-index --index-info' -f
echo
echo Cleaning up
git reflog expire --expire=now --all
rm -rf .git/refs/original/
git gc --prune=now --aggressive
echo
echo All done!
echo Check that the history is OK by running:
echo git log --oneline
# Store the original line
h
g
# Delete the original path
s/[0-9]+ [0-9a-f]+ 0(.*)/0 0000000000000000000000000000000000000000 0\1/
p
# sed workaround: we need to execute a t command so that the next s/// is taken into account
t next
: next
# Restore the original line
g
# Keep the target files, but move them to the top
# Multiple regular expressions matching different names of the module
s/([0-9]+ [0-9a-f]+ 0).*submodule-directory\/(.*)/\1\t\2/
s/([0-9]+ [0-9a-f]+ 0).*older-submodule-directory\/(.*)/\1\t\2/
# If the extracted module should be placed in a subdirectory instead of the root, use something like:
# s/([0-9]+ [0-9a-f]+ 0).*submodule-directory\/(.*)/\1\tnew-root-directory\2/
# If other ways of detecting the target files should be used instead of subdirectory names, adjust the regular expressions accordingly
# If this didn't match, don't print this line
T end
# else print the new line, with the files moved to the top
p
: end
# Delete the buffer so that it doesn't get printed again
d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment