Skip to content

Instantly share code, notes, and snippets.

@mbbx6spp
Last active May 26, 2024 23:00
Show Gist options
  • Save mbbx6spp/1553672 to your computer and use it in GitHub Desktop.
Save mbbx6spp/1553672 to your computer and use it in GitHub Desktop.
Retaining Git history of subdirectory from parent repository

Subdirectory Git Repository

This is a mini howto on moving a subdirectory to its own repository retaining history

Howto

Assume PARENT is the original parent Git repository (locally) and CHILD is the new local repository that you wish to create from a subdirectory, retaining all of its history from the PARENT repository; PARENT_PATH and CHILD_PATH are the paths to PARENT and CHILD respectively; SUBDIR is the relative path within the repository under extraction:

  1. git clone --no-hardlinks PARENT_PATH CHILD_PATH
  2. pushd CHILD_PATH
  3. git filter-branch --subdirectory-filter ${SUBDIR} HEAD -- --all
  4. git reset --hard
  5. rm -rf .git/refs/original/
  6. git reflog expire --expire=now --all
  7. git gc --aggressive --prune=now
  8. popd

Have fun and ENJOY! @SusanPotter

Heckle me in good spirits on Twitter ;) What Git hacks can you send my way? Cheers!

#!/usr/bin/env bash
PARENT_PATH=$1
CHILD_PATH=$2
SUBDIR=$3
git clone --no-hardlinks ${PARENT_PATH} ${CHILD_PATH}
pushd ${CHILD_PATH}
git filter-branch --subdirectory-filter ${SUBDIR} HEAD -- --all
git reset --hard
rm -rf .git/refs/original/
git reflog expire --expire=now --all
git gc --aggressive --prune=now
popd
@dmcguire81
Copy link

I'm not sure if I can issue a pull request on a gist. However, you might be interested that I fixed a defect in the script provided; the bare word SUBDIR is used where the variable ${SUBDIR} is required.

@mbbx6spp
Copy link
Author

I'm not sure if I can issue a pull request on a gist. However, you might be interested that I fixed a defect in the script provided; the bare word SUBDIR is used where the variable ${SUBDIR} is required.

Thank you @dmcguire81. Updated for posterity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment