Search code examples
gitgit-mergegit-rebasegit-remote

Moving Git branch with history to new repo


I have a Git repo with multiple projects on different branches

  • master*
  • frontend
  • backend
  • api

I'd like to break these out into different standalone repos. I created new repositories for each already. I'd like to have each branch and all their commits history moved to their new individual repository.


Solution

  • If each branch contains only the corresponding code, then this is pretty simple. It's actually even simpler to just create the new repo with git clone --single-branch --branch <original-repo-url>, but if you've already inited and just want to bring in the history, you could do something like

    git fetch <original-repo-url> +frontend:master
    

    You'll get weird behavior if you haven't created the first branch in the new repo - so in that case you'd first just create some dummy commit and then detach from the branch so that the update will go through.

    git commit --allow-empty -m temp 
    git checkout --detach
    git fetch <original-repo-url> +frontend:master
    git checkout master
    

    On the other hand, if each of your branches contains all of the code, and you want to rewrite the history for each "new" repo to only include the relevant code, then you probably want to use git filter-branch. It has many options, so without more specific details I can't say exactly what options you'd use, but the subdirectory filter may be of interest.

    Docs at https://git-scm.com/docs/git-filter-branch