Skip to content

Instantly share code, notes, and snippets.

@gowon
Last active March 26, 2024 13:15
Show Gist options
  • Save gowon/a36d7622063bd8567f92342f0462ffc5 to your computer and use it in GitHub Desktop.
Save gowon/a36d7622063bd8567f92342f0462ffc5 to your computer and use it in GitHub Desktop.
Prepend git commit message with issue ticket number(s), derived from branch name, using Powershell

Prepend Commit Messages

Passing arguments to Powershell

At this stage, Git supplies the path to the commit message as the first argument; this can simply be used in the script block. An alternative way would be to export the variable as an environment variable, and grab that in the PowerShell script, as shown in https://stackoverflow.com/a/56758774

This (and other) git hook can be used by default by setting the config globally:

git config --global core.hooksPath /path/to/my/centralized/hooks

For a more granular, repository-level approach, you can set a directory that is under version control to be your git hooks directory, e.g., MY_REPO_DIR/.githooks and execute this command after cloning:

git config --local core.hooksPath .githooks/

References

#!/bin/sh
echo
exec pwsh -NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command ".\.git\hooks\prepare-commit-msg.ps1 '$1'"
exit
# https://medium.com/better-programming/how-to-automatically-add-the-ticket-number-in-git-commit-message-bda5426ded05
# https://sqlnotesfromtheunderground.wordpress.com/2018/01/01/git-pre-commit-hook-with-powershell/
# https://gist.github.com/bartoszmajsak/1396344
# https://githooks.com/
[CmdletBinding()]
Param(
[Parameter(Mandatory = $True, Position = 0)]
[string]
$MessagePath
)
$message = Get-Content -Path $MessagePath
$tickets = [string]::Empty
$branch = & git rev-parse --abbrev-ref HEAD | Out-String -NoNewline
$matches = [Regex]::Matches($branch, "(?:\w+\/)*([a-zA-Z]{2,}[-_]\d+)");
foreach ($match in $matches) {
if ($match.Success) {
$tickets += "[$($match.Groups[1].Value.ToUpper())] "
}
}
"$($tickets)$($message)" | Out-File $MessagePath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment