Dumb Move
Moving files between Git repos is easy. Just move the files from one directory to another. Delete from the first repo, add to the second.
Another Way
Moving files between Git repos while preserving the Git history is not so easy. This essentially involves rewriting Git history. Fortunately the git masters created some options to support this operation.
On Original Repo
bash-4.1$ git subtree —prefix= -b
This creates a new branch containing only the files within the subtree idenfitied by ‘dir to move’.
On New Repo
bash-4.1$ git pull —rebase ../repo1
Apply the branch in the original repo to the new repo. This preserves everything: paths, files, and history.
Move Files to a New Base Directory
Combining git-ls and git-filter-branch, you can move a file or directory from one repo to another while changing the base directory in the target repo.
Apply the Less-dumb Move
Follow the steps above to get the files into the new repo.
Use filter-branch to Rewrite History
export TAB=$t
git filter-branch -f --index-filter 'git ls-files -s | sed -E "s%${TAB}*%${TAB}%" GIT_INDEX_FILE=$GIT_INDEX_FILE.new git update-index --index-info && mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"’ HEAD`
Explaination
Apply a filter-branch command from the HEAD of the current branch. Pass in the following index filter:
- Perform a ‘ls-files’ command to list all the files
- Pipe this list to sed to change the file paths to ‘new directory’
- Pipe the result of this to the git ‘update-index’ command, creating a new index.
- Once the new index is created, replace the old index with this new index