Skip to content

Instantly share code, notes, and snippets.

@nohwnd
Created January 26, 2020 10:15
Show Gist options
  • Save nohwnd/0bd2dc5b178d1bf2f8443611ae82de2f to your computer and use it in GitHub Desktop.
Save nohwnd/0bd2dc5b178d1bf2f8443611ae82de2f to your computer and use it in GitHub Desktop.
PSGitRoot module
$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
#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