Moving files from a Git repository to another keeping history
Yesterday I had to move a few files from a Git repository A to repository B while working on a client’s project. Today I had to do it again on another project. Again I had to think about the sequence of commands I had used. For this reason I’m posting this here.
Prepare repository A (the source)
git clone --no-hardlinks /path/to/sourcerepository repositoryA cd repositoryA # remove remote origin just so we can't break anything in the source repository git remote rm origin # filter for desired files git filter-branch --subdirectory-filter directory HEAD # move around files, etc. # then commit git add . git commit -m"isolated files"
In line #1 we clone the source repository so we can’t break the original one, we also remove the remote in line #4 so no links back to the source repository exist. Next using the filter-branch command we filter out everything but the directory we want to keep. Read more…
Pull files to new repository
git clone repositoryB_URL repositoryB cd repositoryB git remote add repositoryAbranch /path/to/repositoryA git pull repositoryAbranch master git remote rm repositoryAbranch
