I would like to share some useful git snippets, which I’ve used in my git hooks. Snippets originally written in PowerShell but can be easily rewritten for your favorite language.
Here are the full sources
Get Current Branch Name
git rev-parse --abbrev-ref HEAD
Safely Resolve Ref
git rev-parse --verify --quiet $Ref
It returns hash of the valid ref, or $null for invalid ones.
Test if One Commit is Fast-forward for Other
function Test-FastForward
{
param
(
[string] $From,
[string] $To
)
$From = git rev-parse $From
$mergeBase = git merge-base $From $To
$mergeBase -eq $From
}
Get Repo Root Path
git rev-parse --show-toplevel
Get Commit’s Originating Branch
function Get-OriginatingBranch
{
param
(
[string] $Ref
)
$branches = @(git branch --all --contains $Ref) | `
ForEach-Object { $_ -replace "\*? +" -replace "remotes/" }
foreach ($branch in $branches)
{
$refs = git rev-list "$Ref^..$branch" --first-parent
if ($refs -contains $Ref)
{
return $branch
}
}
}
This function is not 100% reliable, because it checks the branches that contains commit directly (not via merge). It could return wrong result, if the branch was created after the commit was made.
(inspired by https://github.com/SethRobertson/git-what-branch/)
Secondly this check is not detects commits from pull merges. I have implemented check for pull merges as well, but it is even more unreliable.