GIT - Extract a Subdirectory into a Separate GIT Repository

This howto shows how to extract a subdirectory into a separate GIT repository.

Assumptions

  • Your main GIT repo is /var/lib/git/giantproject.git
  • You want to extract /var/lib/git/giantproject.git/path/to/subproject into a separate /var/lib/git/subproject.git bare repo
  • You want to remove the subproject subdirectory from your main repo and ARE WILLING TO MESS UP YOUR MAIN REPO'S HISTORY (forcing all clients to clone again)

Extract the subdir into a new GIT repo

#!/bin/bash

ORIG_REPO="/var/lib/git/giantproject.git"
SUBDIR="path/to/subproject"
NEW_REPO="subproject"

# ------------------------------------------------------

cd "$(dirname $ORIG_REPO)"
git clone --no-hardlinks $ORIG_REPO $NEW_REPO

cd $NEW_REPO
git filter-branch --subdirectory-filter $SUBDIR HEAD

git remote rm origin
rm -r .git/refs/original/
git reflog expire --expire=now --all

git gc --aggressive
git repack -ad
git prune

# ------------------------------------------------------

cd "$(dirname $ORIG_REPO)"
git clone --bare $NEW_REPO $NEW_REPO.git

Delete the subdir from the original GIT repo

#!/bin/bash

ORIG_REPO="/var/lib/git/giantproject.git"
SUBDIR="path/to/subproject"

cd $ORIG_REPO
git filter-branch --index-filter "git rm -r -f --cached --ignore-unmatch $SUBDIR" --prune-empty HEAD

rm -rf refs/original/
git reflog expire --expire=now --all
git repack -ad
git gc --aggressive --prune=now

social