Set up a GitHub Branch Protection Rule to require the Repository’s code owner’s approval for branch merging and safeguard the codeowner file.
Step 2: Include the following code snippet in a file named CODEOWNERS.
Note: Insert the relevant user. For demonstration purposes, I am using the user @saurabhpanth
Step 3: Establish a branch protection rule for the specific branch where you intend to implement the codeowner branch policy.
Navigate to the Repository, then access the settings, and select “Branches.”
Step 4: Complete the necessary sections such as the branch name (where you establish branch protection), select the checkbox for “Require a pull request before merging,” and then select the checkbox for “Require review from Code Owners.”
Place a checkmark next to “Require status checks to pass before merging,” and finally, ensure you check the box that says “Do not allow bypassing the above settings.” Finally, click on “create” to finalise the process.
Henceforth, whenever you generate a Pull Request for the codeowner branch protection rule, you will observe that both the codeowner’s and reviewer’s approval are necessary.
Protecting the CODEOWNERS file.
Step 1: Upon ensuring the availability of the CODEOWNERS file in the targeted branches, navigate to the default branch, access the Actions tab, and proceed to establish a .github/workflow.
Step 2: Generate a file named codeowners.yml within the workflow, and include the provided code snippet as shown in below
name: CODEOWNERS Check
on:
pull_request:
paths:
- '**/CODEOWNERS'
jobs:
check-changes:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Check for CODEOWNERS changes
run: |
if [ -f "CODEOWNERS" ]; then
echo "Changes detected in CODEOWNERS file. Please review and seek necessary approvals before merging."
exit 1
fi
Step 3: Following the creation of the codeowners.yml file, push the changes to the corresponding branches, if required.
Below are the steps for Verification/validation of above implemented changes:
Initiate a pull request that mandates two approvals: one from the designated reviewer and another from the assigned code owner, ensuring that both approvals are secured before merging the pull request.