Private/Get-GitRoot.ps1
|
<#
.SYNOPSIS Returns the root directory of the current git repository. .DESCRIPTION For a bare repo, returns the bare repo directory itself. For a worktree, returns the common git dir (the bare repo root). #> function Get-GitRoot { [CmdletBinding()] [OutputType([string])] param( [string] $Path = (Get-Location).Path ) $gitDir = git -C $Path rev-parse --git-common-dir 2>$null if ($LASTEXITCODE -ne 0) { throw "Not inside a git repository: $Path" } # git returns relative or absolute; resolve to absolute if (-not [System.IO.Path]::IsPathRooted($gitDir)) { $gitDir = Join-Path $Path $gitDir } # For a bare repo the common dir IS the repo root # For a worktree inside a bare repo, common dir points to the bare repo $gitDir = (Resolve-Path $gitDir).Path # If common dir ends in \.git, the repo root is one level up if ($gitDir -match '\\\.git$') { return Split-Path $gitDir -Parent } return $gitDir } |