Enforce Branch Naming Convention Using Husky.NET

Add Pre-Commit Hooks

To set up Husky.NET with a dotnet project, please follow the instructions in this link. Next, you’ll need to establish a branch naming convention using Husky.NET. To do this, create a pre-commit hook script in the .husky directory that was generated by Husky.NET.

dotnet husky add pre-commit "branch naming convention"

Prepare Branch Naming Convention Script

Now, we will create a PowerShell script to enforce branch naming conventions. In this instance, we will utilize PowerShell to guarantee adherence to branch naming conventions. A PowerShell script for validation needs to be created and can be stored anywhere in your repository. It is recommended to save this script under the .husky folder.

$branchName = git rev-parse --abbrev-ref HEAD
$pattern = '^(topic)\/((\d+)(\.\d+)?(\.\d+))\/(\d+)\-(\w.*)$|Release_\d.*'
if ($branchName -notmatch $pattern) {
    Write-Output "Error: The branch name does not conform to the required naming convention. Please use the format 'topic/<version>/<azure-task-id>-<description>' or 'Release_<version>'." -ErrorAction Stop
    Exit -1;

Setting Up Branch Naming Validation in Husky.NET Task Runner

Let’s proceed by adding the PowerShell script to the Husky.NET taskrunner. To begin, we should navigate to the .husky folder within our repository. Inside this folder, locate the task-runner.json file. Within this file, we will configure our PowerShell script as a task that can be executed in pre-commit Git hooks.

   "tasks": [
         "name": "Branch Naming Convention",
         "command": "pwsh",
         "args": [".husky/pre-commit-branch-naming-convention.ps1" ]

Configure Pre-Commit Hooks

To configure the pre-commit hook, access the file in the .husky folder. Then, include a command to trigger the branch naming convention task execution.

. "$(dirname "$0")/_/husky.sh"
dotnet husky run --name "Branch Naming Convention"
/// other tasks.

Now, every time you try to commit, Husky.NET will check if your branch name adheres to the naming convention. If it doesn’t, the commit will be aborted, and you’ll see an error message.

« Integrate GitHooks using Hu...