Search code examples
gitgit-rebasegit-pull

How to overwrite local history with remote?


Recently I had to squash commits due to several bad commits. Simply doing git pull --rebase origin master worked for me but my teammate already had merged new history on top of old history. So I want to know is if it is possible to overwrite local history?

Let's say there are three timelines in branches remoteNew, localOld and localNew has hour old commit.

Following works and completely overwrites old history with new history. Though thing to note here is, oldHistory had no new commits after newHistory was created.

git checkout localOld
git pull --rebase origin remoteNew

Following does not work as I would want. Instead of overwriting local history, it creates a merge with conflicts.

git checkout localNew
git pull --rebase origin remoteNew

I believe this is happening because local has new commit. Though what I really want is git push --force like result but for pull. Other way would be to just replace master branch with new branch and rename it. Any other option to overwrite local history?

Note: Would like to clear that this is old repository but team isn't working on it yet, we are in initial stage of adopting git and finalizing workflow before entire team starts working on it.


Solution

  • To overwrite local history with remote history, will remove all files, where are only on local history. So be carefully!

    git fetch --all
    git reset --hard <remote>/<branch-name>
    

    So with git fetch you download the latest remote history. With git reset you reset the branch to that what you just fetched.

    For more information, look at this similar question: How do I force "git pull" to overwrite local files?