See other projects

Moving a directory in git to another repo

I wanted to move a directory from one repo to another, keeping the commit history and without introducing new noise to the commit history. Summarizing what I've learned from a few different sources, here's how I accomplished it.

Let's say we want to move only "dir/directory_src" of "repo_one" to "dir/directory_dest" of "repo_two" (using a shell in Linux):

mkdir ~/repos
cd ~/repos
git clone https://servername/repo_one
cd repo_one
(disconnect from any remotes)
git remote rm origin
(run the following and look at the resulting filenames to see if they look correct)
git ls-files -s | sed "s-\tdir/directory_src/-\tdir/directory_dest/-"
(rewrite history so that "dir/directory_src" moves to "dir/directory_dest")
git filter-branch --index-filter  'git ls-files -s | sed "s-\tdir/directory_src/-\tdir/directory_dest/-" | GIT_INDEX_FILE=$GIT_INDEX_FILE.new git update-index --index-info && if [ -f "$GIT_INDEX_FILE.new" ]; then mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"; fi' HEAD
(delete the directory .git/refs/original, it's a backup copy)
cd ~/repos/repo_one

(run the following and look that files in dir/directory_dest aren't included)
git ls-files | egrep -v ^dir/directory_dest/
(rewrite history and remove all other files)
git filter-branch --tree-filter 'rm -rf $(git ls-files | egrep -v ^dir/directory_dest/)' -- --all
(delete empty commits. optional)
git filter-branch --commit-filter 'git_commit_non_empty_tree "$@"' HEAD
Now let's copy the files into repo_two.
cd ~/repos
git clone https://servername/repo_two
cd repo_two
git remote add from_repo_one ~/repos/repo_one
git pull from_repo_one master
git remote rm from_repo_one
(after confirming that everything looks right,)
(run git push.)
"repo_two" should now contain "dir/directory_dest" and all of its contents.

Note: when using the filter to remove other files outside of the directory might keep files around if the names that contain spaces or tabs.

References:
Moving files from one Git repository to another
How can I move a directory in a Git repo