xsilmarx
xsilmarx

Reputation: 749

Can git be configured to prevent rebase of already published commits?

I want to use the git pull --rebase instead of merge but with this approach one can accidentally rebase commits that were already pushed to another remote.
In this case the merge on pull is mandatory.

Is there a way to configure git so it rejects the rebase if some of the commits that are going to be rebased was already pushed to other remote?

Upvotes: 9

Views: 1292

Answers (2)

Joseph K. Strauss
Joseph K. Strauss

Reputation: 4913

Try this command:

git rebase --onto <remote>/<branch-name> $(git rev-list HEAD \
 --not --exclude=$(git rev-parse --symbolic-full-name HEAD) \
 --glob=refs/* --reverse | head -1)~

This will rebase only commits that were done on the current local branch.

If you want to include local changes to other branches that were not pushed yet change the --glob=refs/* expression to --remotes. Please be aware, though that you may push these local branches in the future, so use with caution.

Clarification: Of course, since you are not using git pull, you will need to execute a git fetch prior to rebasing. (I happen to prefer git fetch + git rebase or git merge, so that I can be in control of what I am rebasing onto or merging.)

Upvotes: 1

CodeWizard
CodeWizard

Reputation: 142522

You can write hook that check to see if any commit within the range of the commits are already in the targeted branch, if so do what ever you want (like rejecting the push)

Using the git commands git branch --contains <commit1> ... <commit_n> you can check if the give branch contains any of the given commits.


Sumarry

git does not have anything out of the box for you, you will have to write some custom made code to do it, but you can use the git branch --contains to find out if the branch already has the given commit in it.

Upvotes: 0

Related Questions