Search code examples
gitrepositorysparse-checkout

git move portion of old repository to a new repository


I've a repository which contains several directories at the root, e.g.

gitroot/a
gitroot/b
gitroot/c

And I would like to create a new git repository from only the contents of a, whilst retaining its history. Is this possible? I've seen the sparse checkouts, but I'm not sure how I could use this to create a brand new repository (with relevant history) from a subdirectory.


Solution

  • After cloning your existing repository, you can use filter-branch

    git filter-branch --subdirectory-filter a -- --all
    

    After that;

    git clean -d -f  // Remove untracked files from the working tree
    git gc --aggressive // Cleanup unnecessary files and optimize the local repository
    git prune  // Prune all unreachable objects from the object database