Modules/businessdev.ALbuild.Apps/Private/Get-BcRepositoryCommitCount.ps1
|
function Get-BcRepositoryCommitCount { <# .SYNOPSIS Returns the number of commits in a git repository, for the 'no-of-commits' version token. .DESCRIPTION Mirrors the ALbuild V1 versioning behaviour: 'git rev-list --count --all' (all refs) from the repository working tree. Isolated in its own function so the version stamping can mock it in tests and so the single git touch is easy to find. Throws a clear, actionable error when the path is not a git working tree or git is unavailable - a 'no-of-commits' schema cannot produce a valid version without it. .PARAMETER RepositoryRoot The git working tree to count commits in. .OUTPUTS System.String - the commit count (numeric). #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $RepositoryRoot ) # Merge git's stderr into the output for a useful failure message, but neutralise the error # preference around the call: under Windows PowerShell 5.1 a native command writing to stderr via # 2>&1 surfaces ErrorRecords that, with ErrorActionPreference=Stop, throw the raw git message before # the exit-code check below runs (it passes on PS7 and fails on PS5.1). Gate on $LASTEXITCODE only. $previousPreference = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { $output = & git -C $RepositoryRoot rev-list --count --all 2>&1 } finally { $ErrorActionPreference = $previousPreference } if ($LASTEXITCODE -ne 0) { throw "The 'no-of-commits' version token needs a git repository at '$RepositoryRoot', but 'git rev-list' failed: $($output -join ' ')" } # On success the count is the last (only) stdout line. return "$(@($output)[-1])".Trim() } |