Private/Test-GitRepository.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<#
.SYNOPSIS
Determines if the specified location is a git repository.
 
.PARAMETER Path
The path to test.
 
.OUTPUTS
[Boolean]
 
.EXAMPLE
$isRepo = Test-GitRepository;
This example, checks if the current directory is a git repository.
 
.EXAMPLE
$isRepo = "C:\project\app\app.csproj" Test-GitRepository;
This example, checks if the current file is in a git repository.
#>


function Test-GitRepository
{
    Param(
        [Parameter(ValueFromPipeline)]
        [string]$Path
    )

    if ([string]::IsNullOrEmpty($Path))
    {
        $Path = $PWD;
    }
    elseif (-not (Test-Path $Path))
    {
        return $false;
    }
    elseif (Test-Path $Path -PathType Leaf)
    {
        $Path = Split-Path $Path -Parent;
    }

    try
    {
        Push-Location $Path;
        return (-not ((&git status | Out-String) -match '(?i)not\s+a\s+git\s+repository'));
    }
    finally { Pop-Location; }

    return $false;
}