I want to enforce branch naming conventions in my GitHub repository before branches are created/pushed, not just validate them after creation.
For instance, these are some rules
Do not allow anything other than these. Ex: feat/, bug/ etc.
I've tried the below GitHub Actions workflow but the issue is that, this only validates after the branch is created.
(.github/workflows/branch-naming.yml):
name: Branch Naming Convention Check
on:
create:
branches:
- '**'
jobs:
branch-naming-rules:
runs-on: ubuntu-latest
steps:
- name: Check branch name
run: |
BRANCH_NAME=${GITHUB_REF#refs/heads/}
VALID_PATTERNS="^(feature|release|hotfix|bugfix)/JIRA[0-9]+-[a-zA-Z0-9-]{1,30}$|^(main|develop)$"
if ! [[ $BRANCH_NAME =~ $VALID_PATTERNS ]]; then
echo "Branch name invalid"
exit 1
fi
I also looked into the following but none of these serve what I am looking for.
I could enforce only at the time of PR requirements but doesn't prevent invalid branch creation proactively
I am also exploring git hooks but appears ineffective to me for two reasons
Sorry for the long explanation. The question is... Is there a way to enforce branch naming conventions at creation time on GitHub remote repository? I want to prevent developers from even creating/pushing branches with invalid names, rather than catching them after creation or at PR time.
Final rule that I used based on the answer
Note: Unable to set the character rule though /JIRA[0-9]+-[a-zA-Z0-9-]{1,30}
I think your issue should be solvable with Github's Rulesets.
Rulesets are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, and GitHub Enterprise Cloud.
You can create a new ruleset by going to your repo Settings -> Rules -> Rulesets -> New Ruleset -> New Branch Ruleset
. Under Targets
you have to include all branches and exclude your pattern. Under Rules
you have to check the Restrict creations
rule.
With this setup you restrict the creation of all branches, except the ones that follow the given regex. You can even add a bypass list here.
Hope this helps!