Skip to content

Instantly share code, notes, and snippets.

@timkinnane
Last active August 11, 2024 22:29
Show Gist options
  • Save timkinnane/6daa212f7248c03a3e0936f5db948ead to your computer and use it in GitHub Desktop.
Save timkinnane/6daa212f7248c03a3e0936f5db948ead to your computer and use it in GitHub Desktop.
Apply branch name format check on commits

Enforce branch name conditions with git hooks

The pre-commit git hook tests branch name against a text pattern.

If commits don't match the pattern, they will error and contributors will have the opportunity to rename the branch before trying to commit again.

Patterns

The example pattern ensures branch names are:

  • scoped by type of change and team owner
  • types feat|fix|spike|chore|docs|test|build
  • lowercase team name/initial/acronym (hyphenated), e.g. mobile-team
  • any valid name under scope (up to your convention)

Setup

First update .git/config to set a path for hooks.

This is so your hook file can be committed to source control.

[core]
	hooksPath = .githooks

Then copy the hook file to .githooks/pre-commit.

Example

See matching and mismatching branch name examples on Regexr.

#!/usr/bin/env bash
LC_ALL=C
local_branch="$(git rev-parse --abbrev-ref HEAD)"
valid_main_regex="^(HEAD|master|main|trunk)$"
valid_branch_regex="^(feat|fix|spike|chore|docs|test|build)\/[a-z-]+\/[a-z0-9._-]+$"
message="
There is something wrong with your branch name.
Please adhere to this contract: $valid_branch_regex
Branch name: $local_branch
"
if [[ $local_branch =~ $valid_main_regex ]] || [[ $local_branch =~ $valid_branch_regex ]]
then
exit 0
else
echo "$message"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment