How to combine two unrelated git repositories, preserving history

旧街凉风 提交于 2019-11-30 13:08:05

While @codeWizard's reply was helpful, that approach didn't retain the timestamps the way I wanted. It did lead me down a rabbit hole that helped me find a solution though...

  1. Create a new, blank repository

    git init
    
  2. Add and fetch the old repositories as remotes

    git remote add -f oldRepoA ../oldRepoA
    git remote add -f oldRepoB ../oldRepoB
    
  3. Export the combined commit history by timestamp and hash, pipe the output to sort, discard the timestamps via cut, and then pipe the list of chronologically sorted hashes to xargs, which runs a shell script to export a patch for each individual hash and then immediately apply the patch to the new repo.

    git log --all --oneline --format="%at %H" | sort | cut -c12- | 
        xargs -I {} sh -c 
            'git format-patch -1 {} --stdout | 
             git am --committer-date-is-author-date'
    

The --committer-date-is-author-date is key to keeping the original timestamps. There might be a better way of doing this, but this works well enough for my use case!

You will have to write a script that will do it.

How to do it

  1. get a list of all your commits timestamps per branch

    # print out the commits time stamp & sha-1 of each commit
    # do it for all your branches
    git log --oneline --format="%at %H"
    

  2. Combine the 2 lists together and sort them by the time stamp using any sort tool (sublime, unix sort etc)

  3. Checkout new branch starting the first commit you have in your files

    git checkout <first commit id>
    

  4. Create new branch starting from this commit

    git checkout -b <new_branch_name>
    
  5. Loop over all the other commits and use cherry-pick to bring them into your branch (script)

    git cherry-pick <next commit id>
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!