Roman
Roman

Reputation: 763

Get information that my local feature branch is not out-of-date with the remote master branch

Intro: We are a team of 10 people actively working on one project. Updates are released very often and it happens that after the changes are published to our GitHub repository, the branch immediately becomes out-of-date with remote master branch, there is no need to run CI/CD and everything else on it, before it gets updated.

For example, I'm working on a feature branch, pushing it to a remote repository, and opening a new pull request. But I cannot know in advance whether my branch is updated according to the master or not. Before each push, I need to manually update the local master branch and do a rebase.

To reduce actions I would like to set up a git pre-push hook that automatically checks if the current branch that I want to push is out of date relative to the master - if so, cancel the push.

On the GitHub page it shows this message: This branch is out-of-date with the base branch

Any ideas how to get this information and cancel pushing to remote? Thanks.

Upvotes: 2

Views: 179

Answers (2)

VonC
VonC

Reputation: 1323973

But I cannot know in advance whether my branch is updated according to the master or not. Before each push, I need to manually update the local master branch and do a rebase.

First:

I need to manually update the local master branch

You just need a git fetch, in order to update your remote tracking branch origin/master. No need to update master itself: you don't work on master anyway.

Second:

and do a rebase.

That is a good practice before any push/pull-request.
But you don't have to do the rebase if your current branch is already on top of origin/master.

And to check that (without rebasing), you can simply check if origin/master is accessible from your current branch HEAD:

git switch myBranch
git branch --contains origin/master

If your own branch is listed, you don't have to rebase, and can push directly.

Upvotes: 1

carnicer
carnicer

Reputation: 523

You may be referring to the --dry-run option of the git push command. If I understand correctly.

It returns 0 in case there are NO commits in the upstream/remote you want to push to that you do not yet have locally.

So you can do something like this in your hook script:

git push --dry-run mirror master || { echo "can't push now, need to fetch & merge/rebase" ; exit 1 ; }

echo "proceed with the push"
git push mirror master

Upvotes: 1

Related Questions