lameprogrammer01
lameprogrammer01

Reputation: 95

Can't push to remote branch after rebase with master?

So I have used git rebase origin/main on my branch - but I want to push these changes to my remote branch. However, whenever I try to use git push -f origin name_of_branch I get the following:

    ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I have pushed to this branch before so I know the remote exists. I just want to update it with the changes of my rebase. I got the idea of using force push from other stack overflow threads but it doesn't seem to work. Anyone got any ideas ? I just want to update the remote branch with the changes of the rebase. thank you

Upvotes: 0

Views: 931

Answers (1)

Pepe Doval
Pepe Doval

Reputation: 84

If you have pushed to this branch before (without -f) and it worked, it seems like the branch is protected against rewrites, which is a common strategy and good practice for main branches (like master or main) as rewriting it would affect anyone basing their work on it.

What you probably want to often do is pull new changes without rebase and then you won't have that problem. But if you really want to rewrite it you need permission to do it. Assuming you do have it, you can find settings to add/remove protection for branches in the admin settings of any usual version control provider (github, bitbucket, gitlab, etc).


How to undo a rebase on a branch that cannot be rewritten

There are several ways you can do this depending on your case, but the next commands should be useful for most scenarios:

git reflog - to see all the commits your HEAD has pointed to (useful to see the situation before the rebase, as you can do git log <hash> for the last hash before the rebase and you'll see every local commit of work that you don't want to lose).

git reset --hard <hash> - to reset the branch to any point in history, for example to the situation before the rebase or to the remote version, depending on how you want to approach it

git cherry-pick <hash> - to apply a single commit in the current branch

Assuming you know the basics of creating/removing branches and commits, with those commands you can restore the situation to the state before the rebase.

For example, you can move your local work to a temporary branch, recreate the branch you rebased resetting it to the remote version and then cherry pick each valuable commit from the temporary branch.

Or if you took note of all the valuable commits after a git reflog, you could simply reset the branch to the state before the rebase and then cherry-pick those commits.

Upvotes: 1

Related Questions