How do I Re-root a git repo to a parent folder while preserving history?

前端 未结 8 1772
予麋鹿
予麋鹿 2020-11-29 23:12

I have a git repo in /foo/bar/baz with a large commit history and multiple branches.

I now want /foo/qux to be in the same repo as /f

8条回答
  •  被撕碎了的回忆
    2020-11-29 23:22

    Most common solution

    In most normal situations, git looks at all files relatively to its location (meaning the .git directory), as opposed to using absolute file paths.

    Thus, if you don't mind having a commit in your history which shows that you have moved everything up, there is a very simple solution, which consists in moving the git directory. The only slightly tricky thing is to make sure git understands that the files are the same and that they only moved relatively to him :

    # Create sub-directory with the same name in /foo/bar
    mkdir bar
    
    # Move everything down, notifying git :
    git mv file1 file2 file3 bar/
    
    # Then move everything up one level :
    mv .git ../.git
    mv bar/* .
    mv .gitignore ../
    
    # Here, take care to move untracked files
    
    # Then delete unused directory
    rmdir bar
    
    # and commit
    cd ../
    git commit
    

    The only thing to be careful, is to correctly update .gitignore when moving to the new directory, to avoid staging unwanted files, or forgetting some.

    Bonus solution

    In some settings, git manages to figure out by itself that files have been moved when it sees new files that are exactly the same as deleted files. In that case, the solution is even simpler :

    mv .git ../.git
    mv .gitignore ../.gitignore
    
    cd ../
    git commit
    

    Again, be careful with your .gitignore

提交回复
热议问题