Is there a way to restrict branch creation pattern in github?

146 views Asked by At

I have a main branch and if someone wants to create new branch then it must start with feature/*, bugfix/*, release/*.

I tried using branch protection rules, but I couldn't find any settings that prevent the creation of these branches which do not match the pattern.

Is there a way to implement this?

2

There are 2 answers

5
Anton Astafiev On

If you wish to protect some central repo you can use pre-commit hooks (see here) for such task. As you can see from here hooks can be client- and server-side. They are in git for a long time and were used in many such situations e.g. in gerrit toolkit. So probably it will not be a big problem to implement some filter based on the name for such hooks. As I know they can be implemented as shell scripts.

So ok, for Github one can use Rulesets feature. Take a look at it.

0
Santhosh Kumar On

you can have an alias to run a shell scrip that will create branch with specific pattern as default and if somebody tries to create a branch with customized name rather than the default branch pattern then delete the branch with a warning message.

sample snippet for the logic:

    local branch_name=$1
    local allowed_patterns=("feature/" "bugfix/" "release/")
    local valid=0
    for patterns in "${allowed_patterns[@]}"; do
        if [[ $branch_name == "$patterns"* ]]; then
            valid=1  # Valid branch name
        fi
    done
    #deleting branch if it is not valid pattern
     if [[ $valid!=1 ]];then
        git branch -D $branch_name
        echo "warning message you want to set"
     fi