Private/Get-GhostVersionForNode.ps1
|
function Get-GhostVersionForNode { <# .SYNOPSIS Returns the newest Ghost version that the installed Node.js can run. .DESCRIPTION Every Ghost version says which Node.js versions it runs on, and Ghost-CLI refuses to install a version that does not match. The newest Ghost often needs a Node.js that is only weeks old. Instead of failing on a machine that is a little behind, the newest version of the current major release that does match is chosen, with a warning. .EXAMPLE Get-GhostVersionForNode Returns, for example, 6.75.0 on a machine with Node.js 22.23.1. #> [CmdletBinding()] [OutputType([string])] param() $npm = if ($env:OS -eq 'Windows_NT') { 'npm.cmd' } else { 'npm' } $node = [version] ((& node --version) -replace '^v') $latest = [string] (& $npm view ghost version) if ($LASTEXITCODE -ne 0 -or $latest -notmatch '^\d+\.\d+\.\d+$') { throw 'npm could not tell which Ghost version is the latest. Pass -Version to choose one yourself.' } # ghost@6 stands for every 6.x.x version. A range with ^ or > would be mangled by cmd.exe on Windows. $major = ([version] $latest).Major $json = & $npm view "ghost@$major" version engines.node --json | Out-String $releases = ConvertFrom-Json -InputObject $json | ForEach-Object { $_ } $candidates = foreach ($release in $releases) { if ($release.version -notmatch '^\d+\.\d+\.\d+$') { continue } # A range such as ^22.23.5 || ^24.22.3: the same major version, and not older. A range in another form # is left to Ghost-CLI to judge. $range = [string] $release.PSObject.Properties['engines.node'].Value $runs = $false foreach ($part in $range -split '\|\|') { if ($part.Trim() -notmatch '^\^(?<minimum>\d+\.\d+\.\d+)$') { $runs = $true continue } $minimum = [version] $Matches['minimum'] if ($node.Major -eq $minimum.Major -and $node -ge $minimum) { $runs = $true } } if ($runs) { [pscustomobject]@{ Version = [version] $release.version; Range = $range } } } $chosen = $candidates | Sort-Object -Property Version -Descending | Select-Object -First 1 if (-not $chosen) { $needed = [string] @($releases)[-1].PSObject.Properties['engines.node'].Value throw "Ghost $major needs Node.js $needed and this machine has Node.js $node. Install a Node.js that fits." } if ([string] $chosen.Version -ne $latest) { $needed = [string] @($releases)[-1].PSObject.Properties['engines.node'].Value $reason = "Ghost $latest needs Node.js $needed and this machine has Node.js $node." Write-Warning -Message "$reason Installing Ghost $($chosen.Version), the newest version it can run." } [string] $chosen.Version } |