Search code examples
gitgithubversion-controlgit-branchgit-merge

How do I transfer a partial history from a git branch to a new repository?


I recently joined a project that has a github repo with a branch that is effectively a fresh start of the entire source tree. I'd like to copy that one branch, starting from just from just that "new source tree" commit, to a new repo, without any remnants of the old source tree lingering in the repo (allowing for the repo to be much smaller). What are the steps to accomplish this?

Here's the "new source tree" commit in question:

https://github.com/ohmage/server/commit/078aecd78d54c6c20e124be3a54979e3a9d81c6f


Solution

  • I don't know if it's necessarily the best way to do it, and I haven't tested it extensively, but I would do something along these lines (assumptions - the branch you want to copy from is called mybranch):

    1. In your current repository, create a new orphan branch, containing the contents of the first commit you want to copy:

      $ git checkout --orphan tmpbranch <hash_of_first_commit>
      $ git commit -a -m 'first commit'
      
    2. Cherry-pick the rest of the commits you want:

      $ git cherry-pick <hash_of_first_commit>..mybranch
      
    3. Push this new orphaned branch to your new repository, as the new master branch:

      $ git push <URL_of_new_repo> refs/heads/tmpbranch:refs/heads/master
      
    4. Delete the tmpbranch so garbage collection will eventually clean up for you:

      $ git checkout mybranch
      $ git branch -D tmpbranch