Skip to content

Instantly share code, notes, and snippets.

@rsmets
Last active May 6, 2016 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsmets/2ba729998499383e9d01a4d37a545244 to your computer and use it in GitHub Desktop.
Save rsmets/2ba729998499383e9d01a4d37a545244 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
#author: Ray Smets
# 5/4/16
#Required: Github's emiller's git-mv-with-history.sh
#https://gist.github.com/emiller/6769886
#This script moves a directory from one git repo to another while keep the commit
#history intact. After this runs you most likely will want to push to the orignal remote.
#Resources Referenced:
#http://blog.mattsch.com/2015/06/19/move-directory-from-one-repository-to-another-preserving-history/
#http://gbayer.com/development/moving-files-from-one-git-repository-to-another-preserving-history/
# Usage:
repoA=$1 #https://raysmets@git.cloud.sophos/scm/cwg/cwg-netguard-tester.git
folder=$2 #src/main/java/net/mojave/netguard/tester/domain
repoA_branch=$3
dest_repo=$4 #https://raysmets@git.cloud.sophos/scm/cwg/cwg-netguard-monitor-client.git
dest_folder=$5 #src/main/java/net/mojave/netguard/monitor/client/newPackage
clone_folder='__git_clone_repoA__'
#clone_folder=$7 #the aboslute path!!!!!
clone_folder2='__git_clone_repoB__'
mkdir -p $clone_folder
echo '++++cloning repo...'
#clone repo
git clone $repoA $clone_folder
#move to new folder
cd $clone_folder
echo '++++removing origin remote'
git remote rm origin
echo '++++filtering branch...'
#removes everything but the folder we need
git filter-branch --subdirectory-filter $folder -- -- all
#move folder into own directory to update remaing commits accordingly
git filter-branch -f --index-filter '
git ls-files -sz |
perl -0pe "s{\t}{\t'$folder'/}" |
GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
git update-index --clear -z --index-info &&
mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"
' HEAD
echo '++++cleaning untracked files'
git reset --hard
git gc --aggressive
git prune
git clean -df
#done with repoA!
cd ..
echo '++++making destination folder...'
mkdir -p $clone_folder2
#clone repoB
git clone $dest_repo $clone_folder2
cd $clone_folder2
#add a repoA folder as a local remote
echo '++++adding a repoA folder as a local remote'
git remote add merge ../$clone_folder
echo '++++pulling from local remote repoA'
git pull merge $repoA_branch
echo '++++moving '$folder' to '$dest_folder
#git-mv-with-history does a mkdir -p
source ../git-mv-with-history.sh $folder=$dest_folder
cd $dest_folder
echo '++++changing owner to you'
sudo find . -type f -name '*.java' -exec chown $USER {} \;
echo '++++Done. Remeber to commit and push the changes to the destination remote & branch!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment