Created
January 26, 2020 10:15
-
-
Save nohwnd/0bd2dc5b178d1bf2f8443611ae82de2f to your computer and use it in GitHub Desktop.
PSGitRoot module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$callStack = Get-PSCallStack | |
$caller = $callStack[1].ScriptName | |
$callerDirectory = Split-Path $caller | |
[string] $PSGitRoot = $null | |
if ((Get-Command 'git' -ErrorAction Ignore)) | |
{ | |
$workTree = @(git rev-parse --git-path $callerDirectory --is-inside-work-tree) | |
if (0 -lt $workTree.Count -and 'true' -eq $workTree[-1]) { | |
$PSGitRoot = Resolve-Path (@(git rev-parse --git-path $callerDirectory --show-toplevel)[-1]) | |
} | |
} | |
Export-ModuleMember -Variable PSGitRoot |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -Modules @{ ModuleName="Pester"; ModuleVersion="5.0.0" } | |
Describe "PSGitRoot" { | |
BeforeAll { | |
if (-not (Get-Command git -ErrorAction Stop)) { | |
throw "git command is not available" | |
} | |
$currentPath = Get-Location | |
} | |
BeforeEach { | |
Get-Module PSGitRoot | Remove-Module | |
} | |
It "Defines the root when imported into a git repository" { | |
New-Item "TestDrive:/repo1/subfolder/subfolder" -ItemType Directory -Force | |
Set-Location "TestDrive:/repo1/" | |
git init | |
Set-Content "TestDrive:/repo1/subfolder/subfolder/import.ps1" "Import-Module '$PSScriptRoot/PSGitRoot.psm1'" | |
& "TestDrive:/repo1/subfolder/subfolder/import.ps1" | |
$PSGitRoot | Should -Be (Resolve-Path "TestDrive:/repo1").ProviderPath | |
} | |
It "Defines the variable with `$null when imported outside of a git repository" { | |
New-Item "TestDrive:/notarepo/subfolder/subfolder" -ItemType Directory -Force | |
Set-Location "TestDrive:/notarepo/" | |
Set-Content "TestDrive:/notarepo/subfolder/subfolder/import.ps1" "Import-Module '$PSScriptRoot/PSGitRoot.psm1'" | |
& "TestDrive:/notarepo/subfolder/subfolder/import.ps1" | |
$PSGitRoot | Should -BeNullOrEmpty | |
} | |
AfterAll { | |
$currentPath | Set-Location | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment