Mylies
Mylies

Reputation: 446

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.

Upvotes: 1

Views: 2346

Answers (2)

jidicula
jidicula

Reputation: 3979

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.

Upvotes: 3

turbopasi
turbopasi

Reputation: 3625

git stash could be helpful in such a case

Use git stash when you want to record the current state of the working directory and the index, but want to go back to a clean working directory. The command saves your local modifications away and reverts the working directory to match the HEAD commit.

Take a close look at the documentaton for git stash. If I understand it right, you first stash your local changes away to get a clean state. Then you can git pull to merge remote changes of the branch. And then add the stash back again, with git stash pop

Remove a single stashed state from the stash list and apply it on top of the current working tree state.

Upvotes: 2

Related Questions