Branch protection via CLI

100 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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):

jq -n '{"required_status_checks":null,"enforce_admins":null,"required_pull_request_reviews":{"dismissal_restrictions":{},"required_approving_review_count":1},"dismiss_stale_reviews":null,"require_code_owner_reviews":null,"require_last_push_approval":null,"bypass_pull_request_allowances":null,"restrictions":null,"required_linear_history":null,"allow_force_pushes":null,"allow_deletions":null,"block_creations":null,"required_conversation_resolution":null,"lock_branch":null,"allow_fork_syncing":null}' \
| gh api -X PUT repos/MY_ORG/MY_PROJECT/branches/main/protection --input -

That way, as part of the JSON, you can set "required_pull_request_reviews" to:

{"dismissal_restrictions":{},"required_approving_review_count":1}

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).