Erich Erich - 2 months ago 7
Git Question

Git commit squashed when merging upstream, how do I update my local repo

I made a few commits in a local repo, pushed those to the remote and created a Pull Request to the upstream master. Those commits were squashed when the PR was merged.

$ git commit A
$ git push origin master
$ git commit B
$ git push origin master


Create PR, squash and merge into upstream master

Then when I do ...

$ git pull upstream master


It does a merge instead of a fast forward since the commit is different. How do I update my local repo to match the upstream master history after commits have been changed/squashed upstream?

I ended up doing the following ...

$ git reset HEAD~2 --hard
$ git pull upstream master
$ git push origin master --force


To match my history, but I'm hoping there's a much cleaner way to do this.

ray ray
Answer

As per this answer, and noted by others, you should run the command below after fetching/updating:

git fetch upstream
git reset --hard upstream/master

More importantly, however, is knowing how to avoid running yourself into a corner.

A Way to Avoid the Problem

To avoid this problem in the future, you should use separate branches for development. You posted:

$ git commit A
$ git push origin master
$ git commit B
$ git push origin master

From your example above, it looks like you were using your master branch for development. That's a big no-no and seems to be the real cause of your problems. Instead, do the following:

git checkout -b changes-for-pull-request
# hack hack
git commit
git push origin changes-for-pull-request
# hack hack
git commit
git push origin changes-for-pull-request

You do not merge your changes-for-pull-request into your master branch. Instead, you send the pull request and point them to your separate topic branch to pull from. You could even rebase your work with their latest to make it easier on them. For example, when you're getting ready to issue your pull request you can rebase as follows:

git checkout master
git pull upstream master  # you never make changes here, so not a problem
git rebase master changes-for-pull-request  # fix conflicts, if any
git push origin changes-for-pull-request

Send the pull request and point them to your changes-for-pull-request branch. When they merge it into their master, it's simply a matter of you doing a git pull upstream master again and you won't have issues.