Skip to content

Instantly share code, notes, and snippets.

@hgraca
Created September 5, 2017 15:19
Show Gist options
  • Save hgraca/9406f9a17afa5e996246d1a8d3cbd1b6 to your computer and use it in GitHub Desktop.
Save hgraca/9406f9a17afa5e996246d1a8d3cbd1b6 to your computer and use it in GitHub Desktop.
Extract repo folder into a new repo
#!/usr/bin/env bash
SOURCE_REPO=${1}
DIR_TO_KEEP=${2}
DEST_REPO=${3}
SOURCE_REPO_DIR='source_repo'
DEST_REPO_DIR='dest_repo'
# Based on:
# https://stackoverflow.com/questions/44777043/git-copy-history-of-file-from-one-repository-to-another/44777296#44777296
# Get Files Ready for Move
#
# Make a copy of repository A so you can mess with it without worrying about mistakes too much.
# It’s also a good idea to delete the link to the original repository to avoid accidentally making any remote changes (line 3).
# Line 4 is the critical step here. It goes through your history and files, removing anything that is not in directory 1.
# The result is the contents of directory 1 spewed out into to the base of repository A.
# You probably want to import these files into repository B within a directory, so move them into one now (lines 5/6).
# Commit your changes and we’re ready to merge these files into the new repository.
echo "Cloning source repo..."
git clone ${SOURCE_REPO} ${SOURCE_REPO_DIR}
echo "Removing what we don't want to keep..."
cd ${SOURCE_REPO_DIR}
git remote rm origin
git filter-branch --subdirectory-filter ${DIR_TO_KEEP} -- --all
cd .. # back to root
echo "Finished preparing source!"
# Merge File into new repository
#
# Make a copy of repository B if you don’t have one already.
# On line 3, you’ll create a remote connection to repository A as a branch in repository B.
# Then simply pull from this branch (containing only the directory you want to move) into repository B.
# The pull copies both files and history. Note: You can use a merge instead of a pull, but pull worked better for me.
# Finally, you probably want to clean up a bit by removing the remote connection to repository A.
# Commit and you’re all set.
echo "Creating destination repo..."
#git clone ${DEST_REPO} ${DEST_REPO_DIR}
mkdir ${DEST_REPO_DIR}
cd ${DEST_REPO_DIR}
git init
echo "Copying what want to keep into the new repository..."
git remote add local_source_repo_branch ../${SOURCE_REPO_DIR}
git pull local_source_repo_branch master
git remote rm local_source_repo_branch
git remote add origin ${DEST_REPO}
git push -u origin master
echo "Finished!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment