Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a pull request is up to date with the target branch

Our project is using protected branches and requires the base branch of a PR to be up-to-date with the target branch in order to merge. We are also using Jenkins to build the unmerged head of the PR because the plugin we use will automatically rebuild all open PRs when the target branch changes, which can quickly clog up a pipeline. So, in the case that a PR is opened without being up-to-date with the target branch, we want to be able to stop the Jenkins pipeline right away and notify the committer that they need to merge first.

So, using the GitHub API, I would like to be able to tell if a pull request is up-to-date with the target branch. The closest thing to this seems to be the "mergeable" attribute on a pull request, but that looks like it only indicates whether a safe auto-merge CAN be done, not whether the branch is already up-to-date.

Is there a direct API json tag that can be looked at? If not, is there a simple way to check this manually with git commands?

like image 729
Brad Cooley Avatar asked Sep 08 '16 16:09

Brad Cooley


People also ask

How do you fix this branch is out of date with the base branch?

make sure you've checked out your branch: git checkout your-branch. get the latest changes from the upstream to your-branch: git pull upstream master. after that, push the changes you've got from upstream: git push origin your-branch. finally, you can go to github page to make sure no more out-of-date is blocking your ...


1 Answers

I don't know whether GitHub exposes this information through their API, but you can detect this manually with Git commands. You want to find what is known as the merge base, and ensure that this commit is the same as the tip of master (or whatever your main branch is).

In the form of a bash script, it would look something like this:

if [ $(git merge-base @ master) == $(git rev-parse master) ]
then
  echo "Your branch is up to date."
  exit 0
else
  echo "You need to merge / rebase."
  exit 1
fi

If you include this script as a build step, then the exit values should cause Jenkins to fail the job if necessary.

As mentioned in Dmitry's answer, with newer versions of Git you can use the --is-ancestor flag for git merge-base to simplify it to one command. The script would then look like this:

if git merge-base --is-ancestor master @
then
  echo "Your branch is up to date."
  exit 0
else
  echo "You need to merge / rebase."
  exit 1
fi
like image 136
Scott Weldon Avatar answered Oct 04 '22 13:10

Scott Weldon