Search code examples
gitgithubdirectorygit-remote

Moving repository one hierarchy down without destroying commits


So right now I have this folder structure:

\frontend
  -- .git/
  -- project 1 folder
  -- project 2 folder

Now we've decided to separate each project on its own repo and also change the remote url for each of them.

How can I make it so it doesn't destroy my commit history for project 1 folder but the next time I do git push the root folder will now be project 1 folder and not frontend ?

I saw this similar question but the accepted answer seems to be wrong (the root folder is still included on the commit)


Solution

  • I think the answer you linked to is indeed what you want: Moving a git repository down a hierarchy level

    Maybe what's not clear is how to apply it exactly to your case, since you're moving things up rather than down. So here it is adapted to your situation:

    # start with a fresh clone because you don't want any "dirty" files here!
    git clone <remote>/frontend.git
    # enter the fresh clone
    cd frontend
    # remove project 2 files
    rm -rf "project 2 folder"
    # move project 1 files up
    mv "project 1 folder"/* .
    rmdir "project 1 folder"
    # create massive change commit
    git add -A
    git commit -m "Moved project 1 up and removed project 2"
    git push
    

    Now, the folder where all this is located, frontend, is not actually part of the repo itself, but rather the name where it's located. You can rename it when you next clone it:

    git clone <remote>/frontend.git "project 1 folder"
    

    That will only change the name for that clone.

    Or you can go on your Git server and rename the repo itself to "project 1 folder".git, assuming your Git host allows it. Of course, doing so will invalidate the remote URL of any sandbox anyone has cloned from this repo in the past, so you'll have to fix those.

    Now, the problem is that project 2 is gone. I think what you might need to do is create two fresh repos on your Git server, one per project. Follow the steps above, stopping just before git push, and do this instead:

    # Create "project 1 folder".git on your Git server and add it as a second remote
    git remote add p1 <remotes>/"project 1 folder".git
    # push to that remote instead of origin - list all branches you want to preserve
    git push p1 master
    

    And the repeat all of the above, reversing the roles of projects 1 and 2.