Search code examples
gitgit-subtree

Git subtree split two directories


I've been following this excellent answer to extract a subdirectory of my git repository into its own repository, while retaining the complete history.

My repository looks like:

src/
    http/
    math/
tests/
    http/
    math/

I want to create a new branch that only contains the src/math and tests/math directories.

If I run the following command:

git subtree split -P src/math -b math

It creates a branch that contains the contents of the src/math directory, but discards the src/math/ prefix.

If I try the same command with two directories:

git subtree split -P src/math -P tests/math -b math

It only extracts the contents of tests/math, ignoring src/math, and also discarding the tests/math prefix.

To summarize, I would like my final repository to look like:

src/
    math/
tests/
    math/

That is, keeping the original directory structure but discarding everything that's not explicitly mentioned in the command-line.

How can I do that?


Solution

  • Depending on your needs you might get away with git filter-branch.

    I'm not entirely sure what you are trying to achieve, but if you merely want to have a repository with two directories removed (in the history?) this is probably your best shot.

    See also Rewriting Git History.

    $ git filter-branch --tree-filter 'rm -rf tests/http src/http' --prune-empty HEAD
    

    This will look into each commit and remove the two directories from this commit. Be aware that this rewrites history (i.e.: alters your commit sha) and will cause headaches if you have a common history with another repository.