My Github Default Branch Protection Rules
Description
I have been using this standard for creating Branch Protection rules in every Github Repo I create following my git flow model.
To Resolve:
-
First, let’s assume you have an empty repo except for a README.md on main. The first thing I do is create a
featurebranch off of main. -
Next, on your
featurebranch, create a file called./.github/workflows/main_protector.yamland fill it in like so:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# https://stackoverflow.com/questions/71120146/allowing-only-certain-branches-to-pr-merge-to-mainmaster-branch name: 'protect_main_branch' on: pull_request: branches: - "main" jobs: check_branch: runs-on: ubuntu-latest steps: - name: Check branch if: github.base_ref == 'main' && github.head_ref != 'develop' run: | echo "ERROR: You can only merge to main from develop branch." exit 1
-
This ensures that the only way our
mainbranch will accept pushes is through an approved Pull Request from thedevelopbranch. -
Here you can search the docs for
head_refversusbase_refbut base is the branch you are merging in TO and head ref is the branch you are doing the request FROM.
-
-
Next, create a branch called
developbased ofmain. It’s important that you base it off main and not the feature branch we just created because we need it to be different so that when we pull request in to it, it won’t say “no changes detected”. -
Next, create a Pull Request from
featuretodevelopand accept it to merge. Then merge fromdeveloptomain. Finally merge back frommainback to yourfeaturebranch. This allows Github to know about yourmain_protector.yamlfile we created because it will be on the main branch.- If you are unfamiliar with the reason for all these pull requests, please refer to my git flow post.
- Next, click on the repo and go to Settings => Branches => Add Rule.
- Branch name pattern:
main - In section “Protect matching branches” Check
Require a pull request before mergingonly and uncheckRequire approvals - Check the main section
Require status checks to pass before mergingand start searching forcheck_branchin the matching workflows. Then check the box forRequire branches to be up to date before merging - Further down, check the box
Do not allow bypassing the above settings - Finally, click Save Changes
- Branch name pattern:
- Now create a rule for ‘develop’:
- Branch name pattern:
develop - In section “Protect matching branches” Check
Require a pull request before mergingonly and uncheckRequire approvals - That’s it, Save Changes
- Branch name pattern:
Comments