Using git reset to merge
My lead says to merge an issue into the main branch, first I should
git fetch git checkout main-branch git reset --hard origin/main-branch # ??? git checkout my-branch git merge main-branch
This appears to correctly fast-forward merge my local main-branch to match origin. Why is this? Shouldn’t it be
git merge origin/main-branch
git pull origin main-branch
What is the difference?
2 Solutions collect form web for “Using git reset to merge”
git fetch will update your remote branches to have all the new commits in them. So
origin/main-branch will be updated afterwards. So when you switch to your local
main-branch and reset to the remote branch, you are resetting the local branch to the updated branch from the remote now.
Usually, you would use
git pull on the
main-branch to get this effect. This also has the huge benefit that in case you had some local commits that were not included on the remote branch, they would get merged automatically. So, be careful as using
reset --hard can result in commits getting lost.
git pull is essentially the same as
git fetch followed by a
git merge, so either is fine. Running
git fetch manually helps if you have multiple remote branches you would want to update (as
git fetch fetches all remote branches by default).
Another very safe option would be to use
git pull --ff-only. This is what I usually do when updating a local branch I do not expect to have any local commits. In case you ever happened to have a local commit that is not part of the remote branch, it will give you a warning and will not merge anything. So you can figure out first, where the commit came from and see for example if you accidentally commited to a wrong branch or something.
git fetch git checkout main-branch git merge origin/main-branch
Would be essentially the same as
git checkout main-branch git pull
So that does seem like a lot better than
git reset --hard origin/main-branch, which just throws away any local commits.
git checkout my-branch git merge main-branch
merges changes from main-branch to my-branch.
To “merge an issue into the main branch” you should rather do (assuming the issue is fixed on
git checkout main-branch git merge my-branch