I created a GitHub Actions workflow that should add a branch protection rule so that a commit on the main branch is only possible via a PR. The PR should have at least 1 reviewer.
I have the following action code:
addMainBranchPolicy:
runs-on: ubuntu-latest
permissions:
issues: read
steps:
- name: Set up branch protection
env:
GH_TOKEN: ${{ secrets.ACCESS_TOKEN }}
REPO_NAME: ${{ github.repository }}
run: |
gh api -X PUT /repos/$REPO_NAME/branches/main/protection --header 'Accept: application/vnd.github.v3+json' --field required_status_checks=null --field enforce_admins=false --field restrictions=null --field required_pull_request_reviews=null
This works fine, and the rule will be created, but I don't know how to add the rule settings for the PR.
I know that I have to change this field required_pull_request_reviews=null
, but I don't know how.
You could pipe a json into "gh api", like this (this works on my machine "as is", it's a cut and paste from my console to this textarea, just replace your org and project name):
That way, as part of the JSON, you can set
"required_pull_request_reviews"
to:You also avoid using the [][] notations to define elements inside elements in the JSON (it's clearer to provide the full Json IMHO).
Note: make sure you have jq installed on your machine (pretty standard to have jq installed nowadays for anyone who's scriptings/bash quite a bit).