Search code examples
gitgithubgithub-actions

GitHub Actions to enforce proper branch names & PR merging


In our project we want:

  • all git branches made against our dev branch to match this regex

    ^(bug|feature|code-cleanup)\/JIRA-\d+-.+$
    

    examples: bug/JIRA-123-fix-login-issue or code-cleanup/JIRA-4567-enable-code-linting

  • all branches made against our qa branch to match this regex

    ^kickback\/JIRA-\d+-.+$
    

    example: kickback/JIRA-123-fix-login-issue-again

  • enforce that if a branch name begins with kickback/ then a PR can only be made against the qa branch.

I have found some GitHub Actions like nicklegan/github-repo-branch-naming-policy-action and deepakputhraya/action-branch-name which allows a global branch name regex pattern enforcement, but it doesn't seem like there is a way to specify different rule for different branch bases. If there was this would take care of the first two bullet point above, but not the 3rd one.

How can I enforce these checks for validating branch names are correct and PRs are made against the correct base branch?


Solution

  • I created repo here which demonstrates one of many ways to do it. HERE

    1. Copy code to your workflow and customize it for your needs
    2. Go to your repo Settings -> rules -> ruleset
    3. Create new rulset -> new branch rulesets
    4. Set target branchas to all.
    5. Set Require status checks to pass -> name it whatever -> chose github actions
    6. Save and enjoy.

    But essentially it's this code:

    name: Check Pull Request
    on: pull_request
    
    jobs:
      check_pr:
        runs-on: ubuntu-latest
    
        steps:
          - name: Check if PR target branch is ok
            run: |
              branch_name=${GITHUB_HEAD_REF}
              echo "pr branch name: $branch_name"
              
              target_branch=${GITHUB_BASE_REF}
              echo "target branch: $target_branch"
              dev_regex="^(bug|feature|code-cleanup)/JIRA-[0-9]+.*$"
              qa_regex="^kickback/JIRA-[0-9]+.*$"
              
              if [[ "$branch_name" =~ $dev_regex ]]; then
                echo "Branch name matches the first regex pattern."
                if [[ "$target_branch" != "dev" ]]; then
                  echo "but doesn't match target branch"
                  exit 1
                fi
              elif [[ "$branch_name" =~ $qa_regex ]]; then
                echo "Branch name matches the second regex pattern."
                if [[ "$target_branch" != "qa" ]]; then
                  echo "but doesn't match target branch"
                  exit 1
                fi
              else
                echo "Branch name does not match any regex. Exiting..."
                exit 1
              fi
            shell: bash
    

    It did took me a while, so I could make some mistakes - if so, please share I'll fix them :)