2

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.

Roman
  • 743
  • 10
  • 21
  • 1
    If the branch is not up to date with its upstream you cannot push anyway — `git` stops you with the error message [updates were rejected](https://stackoverflow.com/search?q=%5Bgit%5D+updates+were+rejected). If you need more than that see https://stackoverflow.com/a/17938274/7976758 and all other answers in the linked question. – phd Jan 31 '21 at 01:37

2 Answers2

1

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
carnicer
  • 494
  • 3
  • 9
1

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250