ps/Modules/Cole.PowerShell.Developer/Public/Find-GitRepoRootFromPath.ps1
2023-05-30 22:51:22 -07:00

38 lines
1.1 KiB
PowerShell

function Find-GitRepoRootFromPath {
<#
.SYNOPSIS
Find the root repository for a given folder, if there is one.
Throws if neither the folder nor it's parents are a git repository.
.PARAMETER Path
The file path to check. Can be presumed as the current folder.
#>
param(
$Path = ((Get-Location).Path)
)
$logLead = (Get-LogLeadName)
$repoRootFound = $false
$rootFolderFound = $false
$workingFolder = (Resolve-Path $Path).Path
do {
if (!(Test-Path $workingFolder)) {
throw "$logLead : Path does not exist or can not be evaluated at [$workingFolder]"
}
$repoRootPath = (Join-Path $workingFolder ".git")
if (Test-Path $repoRootPath) {
$repoRootFound = $true
break
}
$newWorkingFolder = (Get-Item $workingFolder).Parent.FullName
if ([string]::IsNullOrWhiteSpace($newWorkingFolder)) {
throw "$logLead : Can not find a parent folder for [$workingFolder] looking above [$Path]"
}
$workingFolder = $newWorkingFolder
} while ($true)
return $workingFolder
}