Search code examples
gitgit-pull

How to pull git branch without undoing all my changes?


I have a git branch I'm working from and I have screwed it up. I have a bunch of local changes I made and I'm trying to put these changes and this commit into a PR but I can't do that without updating from the branch because they somehow got out of sync. So whenever I run git status I get

Your branch and 'origin/myChanges' have diverged,
and have 1 and 1 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

And everything I've tried with the git pull just blows all of my changes away, but I need to update from the branch before I'm allowed to send the commit to the PR. I've also tried running a force push to have the branch be the same as mine (it's just a small branch I made for this feature so w little risk). I don't know how to git pull in such a way where my changes are not destroyed and blown away, I want to keep everything that is local and I don't care about anything on the branch.


Solution

  • At a high level, your steps in such a situation should be something like:

    1. Stash your local uncommitted changes.
    2. Run git fetch to make sure your local clone knows what refs are on remote.
    3. Rebase your local branch onto origin/myChanges.
    4. Fix up any merge conflicts that occurred.
    5. Pop your stash.
    6. Fix up any merge conflicts that occurred from stash popping.
    7. Force-push with lease your changes to origin/myChanges. If you have multiple developers working on the same branch (which you really, really shouldn't do since it leads to these situations), inform them that you've force-pushed.
    8. Keep working on your changes, then commit and push when you're ready.