Interesting git helpers snippets

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
        [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
        [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

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.


About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s