I'm trying to set up a git hook where it checks if a branch name begins with certain words, only has lowercase letters and is 15 characters or less. I have it partially working. The 'lowercase only' and '15 characters or less' parts of the regex work. I can't get the 'begins with specific words' part of the regex to work.
Here is my git hook pre-push file contents:
#!/usr/bin/env bash
LC_ALL=C
local_branch="$(git rev-parse --abbrev-ref HEAD)"
valid_branch_regex="^(task|master|develop|qa|tb|bug|story)\/[a-z0-9._-]{2,15}$"
message="This branch violates the branch naming rules. Please rename your branch."
if [[ ! $local_branch =~ $valid_branch_regex ]]
then
echo "$message"
exit 1
fi
exit 0
I created a new branch locally called task_7777 and ran git push. The branch name failed the regex check even though the name starts with 'task'.
I only want branch names that start with either "task, master, develop, qa, tb, bug or story", and only allow lowercase letters, numbers, dashes and underscores, and contain 15 characters or less. I tried modelled my code after the example in this post: https://itnext.io/using-git-hooks-to-enforce-branch-naming-policy-ffd81fa01e5e
How do I get the 'begins with specific words' part of the regex to work?
CodePudding user response:
First you need to change the regex to not require the / after the keyword:
^(task|master|develop|qa|tb|bug|story)[a-z0-9._-]{2,15}$
Then you still have the issue that your length restriction only restricts the part after the keyword, which is probably not what you want. To fix this you need to separate the tests since bash does not support lookahead zero-length assertion:
valid_keyword_regex="^(task|master|develop|qa|tb|bug|story)"
valid_length_regex="^[a-z0-9._-]{2,15}$"
If both tests succeed you have a valid branch name.
