How to Extract a Subdirectory as a New git Repository

Some time ago I converted a massive Subversion repository to git. It’s largely legacy projects that are in storage. I’ve been asked to update one project, and felt it would be best to split that project out into its own git repository.

I was able to find an excellent treatment on stackoverflow here. The following are my notes and observations.

  1. Clone the local repository.
    git clone monster-repository project-repository
    cd project-repository

    This creates a working copy that will be manipulated.

  2. In this particular case, I was not interested in any branches other than master.
  3. Disconnect the new repository from the old origin
    git remote rm origin
  4. In this particular case, I was not interested in preserving the tags, especially the one generated during the Subversion to git conversion. This removes all tags.
    git tag -l | xargs git tag -d
  5. This is a cool command. It removes everything except the desired subdirectory, and moves the subdirectory up to the project root directory. In this example, project-directory is the name of the subdirectory for the project that we’re extracting and want to move to the relative root.
    git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter project-directory HEAD
  6. This purges the repository of all unrelated commits and shrinks the repository.
    git reset --hard
    git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
    git reflog expire --expire=now --all
    git gc --aggressive --prune=now
  7. Finally, connect this repository to the new remote, and populate the new remote repository.
    git remote add origin [url]
    git push origin master

I didn’t want to purge the project from the original legacy repository, so I simply deleted the entire project directory, and committed with the message “This directory has been moved to its own git repository found at [url].”.

This entry was posted in Programming and tagged , , , , , , . Bookmark the permalink.

Leave a Reply