gitgithub

How can I completely replace a remote repo with a local repo while preserving both commit histories?


I have two separate repos:

  1. A remote GitHub repo with an existing commit history, issues, and a wiki.
  2. A local git repo with its own distinct commit history.

I want to replace the contents of the remote repository with those of the local repository, effectively making the remote an exact copy of the local one.

I have not made any attempts at this as I do not want to risk losing anything.

Edit: All commits in the local repo have timestamps AFTER the most recent commit in the remote repo.


Solution

  • This ended up being my solution, since my files were different enough that I didn't have to resolve many merge conflicts:

    Add the remote repo to the local repo:

    git remote add remote-repo ../remote-repo
    git fetch remote-repo
    git checkout -b remote-repo-history remote-repo/main
    

    Merge histories:

    git checkout main
    git merge --allow-unrelated-histories remote-repo-history
    git checkout --ours .
    # here I needed to first remove all my remote repo files
    git add .
    git commit -m "Resolved conflicts, prioritizing local files"
    

    Check merge is successful: git log --oneline --graph --all

    Then I deleted the branch and pushed:

    git branch -d remote-repo-history
    git remote add origin <new-remote-url>
    git push -u origin main
    

    Disclaimer that I am very unfamiliar with git and this solution is likely not elegant whatsoever but it works to fulfill all my requirements in the original post. I should also note that this is a solo project and I do not know how others would be affected. I do not recommend following this.