Search code examples
gitgit-filter-branchgit-mv

Move git repository to a subdirectory in the same path while preserving all of its history


I have a git repository with >100 commits that I initialized awhile back in the following path:

/Users/myusername/

However, all of my commits are actually for files in the path:

/Users/myusername/excess/folders/not/requiring/version/control/project_root/

I should have initialized the repository in project_root/, because I don't need to version control anything in the upper directories.

Is there any easy way of changing the path of my repository so that the top level of the repository is project_root/ while also preserving my version history as it is? Are there any extra steps to get this reflected in my remote repository as well or do I just commit and push after making the change?


Solution

  • If something goes wrong, you can delete the copied .git* files and start over. Here is what you can do:

    $ cp -r .git* path/to/project_root/
    $ cd path/to/project_root/
    $ git add -A .
    

    When you call git status, all you should see are renames and removes now. If all looks good, you can delete .git* in the previous root.

    Also beware that any files existed in history will remain there, that requires another operation to clean up if you have credential files etc.