The following steps can be followed for filtering a set of folders found in a git repository. It would preseve the given folders and their commits and remove everything else from the repository. This would be useful for moving a collection of folders from one git repository to another with their commit history.
-
Take a copy of the source git repository
cp -r [source-repository-folder] source-repository-copy
-
Remove remotes from the copy to make sure not to ovewrite the source git repositories:
cd source-repository-copy git remote rm origin git remote rm upstream # ignore if an upstream does not exist
-
Filter folders path/to/folder1 and path/to/folder2:
git filter-branch -f --index-filter 'git rm --cached -qr --ignore-unmatch -- . && git reset -q $GIT_COMMIT -- path/to/folder1 path/to/folder2' --prune-empty -- --all git clean -fd
Now execute a git log
command and a tree
command and verify the result. If everything went well, the source-repository-copy folder should only contain path/to/folder1, path/to/folder2 and their commits.