I want to make my current branch exactly the same as my main branch. When I do 'git reset --hard main', it does the job. But then when I push it complains that it is behind.
error: failed to push some refs to 'https://gitlab.bol.io/sequoia/relevanc.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
I tried using logs but it doesn't work... just want to go back to the main branch... how to do this?
A branch in Git is merely a name for a commit. That's just about all it is. So the phrase "make my current branch exactly the same as my main branch" is ambiguous. What is it supposed to mean?
Let's say you have this:
A -- B -- C -- D <- main
\
X -- Y -- Z <- mybranch
When you say you want mybranch
to be the same as main
, you might mean one of two things (at least).
You might mean: "I don't care about Z. I don't care about Y. I don't care about X. I'm sorry I ever made them. I'm sorry about all the work I've done on mybranch
. I want mybranch
to start all over, emanating from where main
is now."
Then there is no need for all this violence (hard reset, force push, etc.). Just delete mybranch
altogether! It serves no purpose:
git fetch
git switch --det origin/main
git branch -D mybranch
git push origin --delete mybranch
Now mybranch
is gone — both locally and on the remote. If you now want to start over, with mybranch
emanating from main
, then start over: make mybranch
:
git switch -c mybranch
git push origin mybranch
Result on the remote:
A -- B -- C -- D <- main, mybranch
As you can see, main
and mybranch
are the same commit, and the separate history of mybranch
is effectively gone.
You might mean: I want to keep X and Y and Z but I want the state of my project in mybranch
to be identical to the state of my project in main
.
Then you would reverse merge mybranch
into main
with the ours
strategy, and then merge main
into mybranch
:
git fetch
git switch --det origin/main
git merge -s ours mybranch
git switch mybranch
git merge origin/main
git push origin mybranch
Result on the remote:
A -- B -- C -- D -- M (identical to D) <- main, mybranch
\ /
X -- Y -- Z
As you can see, main
and mybranch
now point to the same commit, M, which is identical (in content) to D, which was the state of main
; but the history has been preserved.