Skip to content

Instantly share code, notes, and snippets.

@SridharPasham
Created November 21, 2024 11:09
Show Gist options
  • Select an option

  • Save SridharPasham/ccd7c019e7d253b198fa361d44278282 to your computer and use it in GitHub Desktop.

Select an option

Save SridharPasham/ccd7c019e7d253b198fa361d44278282 to your computer and use it in GitHub Desktop.
pre-push git hook for branch name restrictions
#!/bin/bash
echo "Checking for branch naming rule" >&2
echo "Branch name should be Ex: [UserName]_[PBI|Bug|Task][Number]" >&2
# Get username from git config or set to 'user' if not found
username=$(git config --global user.name | sed 's/[^a-zA-Z0-9_-]/_/g')
if [ -z "$username" ]; then
username="user"
fi
echo "Username: $username" >&2
# Define the valid branch name regex pattern
valid_branch_regex="^${username}_(PBI|Bug|Task)[0-9]+$"
echo "Valid branch regex: $valid_branch_regex" >&2
# Get the current branch name
local_branch="$(git rev-parse --abbrev-ref HEAD)"
echo "Current branch: $local_branch" >&2
# Check if the branch name matches the regex pattern
if [[ ! $local_branch =~ $valid_branch_regex ]]; then
echo "Error: Branch name '$local_branch' does not conform to naming conventions." >&2
echo "Please rename your branch to match: ${username}_[PBI|Bug|Task][Number]" >&2
exit 1
fi
echo "Branch name is valid." >&2
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment