Rebase Master
Rebase
While you’ve been working on something, probably you’ve been working on a branch on-and-off, or lots has happened in other branches.
The best solution would be to rebase your branch onto master. This keeps the history tidy and makes things a lot easier to follow.
Update your feature branch from master:
Switch the
masterbranch$ git checkout masterGet
remoteupdates:$ git pullSwitch back to your
localbranch:$ git checkout local_branchMake the
rebasemagic:$ git rebase masterPush your
localbranch toremote:$ git push--forceflag will be needed if you’ve already pushed your branch.$ git push --force
Warning
Think and check twice before using -force flag.
Edited: 2021-04-19
As @renepijl
recommended: It would be better to use --force-with-lease over --force since
--force-with-lease prevents overriding someone else’s works/commits.
From git-scm:
–force-with-lease alone, without specifying the details, will protect all remote refs that are going to be updated by requiring their current value to be the same as the remote-tracking branch we have for them.
Comparing Branches
If you want to compare your local and remote feature branch before “forced
push”:
$ git diff <master_branch_path> <remote_branch_path>
For example:
$ git diff feature origin/feature
Where feature is your local branch and origin/master is your remote branch.
Git - Your branch and ‘origin/xxx’ have diverged
If you receive below error:
Your branch and 'origin/xxx' have diverged,
and have 1 and 1 different commit(s) each, respectively.
It is normal. This happens if you rebase the branch which was previously pushed to the origin
repository. Rebase rewrites history, so after it you’ll have different local and
remote state.
We had a history like this:
... o ---- o ---- A ---- B master, origin/master
\
C branch_xxx, origin/branch_xxx
And we “rewrote” the history like this:
... o ---- o ---- A ---------------------- B master, origin/master
\ \
C origin/branch_xxx C` branch_xxx
The solution:
$ git push origin branch_xxx --force
So the actual state will be like:
... o ---- o ---- A ---- B master, origin/master
\
C` branch_xxx, origin/branch_xxx
As said before:
Warning
Think and check twice before using -force flag, or use –force-with-lease.
For more details:
All done!
Changelog
- 2021-04-19 : Added
--force-with-leaseoption