Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict branch X to be merged only from one specific branch Y in Github

Tags:

git

github

My repository belongs to an organization I created. I want to prevent mistakes during pull requests. For example, accidentally allowing the master branch to be merged from a branch other than development.

How can I accomplish this?

like image 604
Stav Alfi Avatar asked Nov 24 '25 08:11

Stav Alfi


1 Answers

Here is an example of creating a github actions workflow that only allows merging from the staging branch or a hotfix/ branch.

name: Main Branch Protection

on:
  pull_request:
    branches:
      - main

jobs:
  check-branch:
    runs-on: ubuntu-latest
    steps:
      - name: Check branch
        run: |
          if [[ ${GITHUB_HEAD_REF} != staging ]] && ! [[ ${GITHUB_HEAD_REF} =~ ^hotfix/ ]]; 
          then
            echo "Error: Pull request must come from 'staging' or 'hotfix/' branch"
            exit 1
          fi

Within the branch protection rules of the repository, you can enforce that this workflow succeeds before merging is allowed. (You should also have require pull request before merging selected too.) enter image description here

like image 177
cashes11 Avatar answered Nov 26 '25 00:11

cashes11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!