Files
MDHelper/pack/build_installer.ps1
T

137 lines
7.3 KiB
PowerShell

[CmdletBinding()]
param([switch]$NoPause, [switch]$SkipTests)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
# A .cmd launched from PowerShell 7 may inherit incompatible module paths.
$env:PSModulePath = (Join-Path $PSHOME 'Modules') + ';' + (Join-Path $env:ProgramFiles 'WindowsPowerShell\Modules')
$projectRoot = Split-Path -Parent $PSScriptRoot
$logDir = Join-Path $PSScriptRoot 'logs'
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
$logFile = Join-Path $logDir ('build-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.log')
Start-Transcript -Path $logFile | Out-Null
function Invoke-Checked([string]$Program, [string[]]$Arguments) {
& $Program @Arguments
if ($LASTEXITCODE -ne 0) { throw "$Program failed with exit code $LASTEXITCODE" }
}
function Test-PythonCode([string]$Python, [string]$Code) {
try {
& $Python -B -c $Code 2>$null | Out-Null
return $LASTEXITCODE -eq 0
} catch { return $false }
}
function Find-Python {
$candidates = @()
if ($env:MDHELPER_PYTHON) { $candidates += $env:MDHELPER_PYTHON }
$candidates += @(
(Join-Path $projectRoot 'mdhelper_env\Scripts\python.exe'),
(Join-Path $projectRoot 'mdhelper_env\mdhelper_env\Scripts\python.exe'),
(Join-Path $projectRoot '.venv\Scripts\python.exe'),
(Join-Path $PSScriptRoot '.venv\Scripts\python.exe')
)
$launcher = Get-Command py.exe -ErrorAction SilentlyContinue
if ($launcher) {
$detected = & $launcher.Source -3 -c 'import sys; print(sys.executable)' 2>$null
if ($LASTEXITCODE -eq 0) { $candidates += $detected }
}
$onPath = Get-Command python.exe -ErrorAction SilentlyContinue
if ($onPath) { $candidates += $onPath.Source }
foreach ($candidate in $candidates | Select-Object -Unique) {
if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { continue }
if (Test-PythonCode $candidate 'import sys, struct; sys.exit(0 if sys.version_info >= (3, 10) and struct.calcsize(chr(80)) == 8 else 1)') { return $candidate }
}
throw 'Python 3.10+ (64-bit) was not found. Install Python, or set MDHELPER_PYTHON to python.exe.'
}
function Find-InnoCompiler {
$candidates = @()
if ($env:MDHELPER_ISCC) { $candidates += $env:MDHELPER_ISCC }
$candidates += (Join-Path $PSScriptRoot '.tools\InnoSetup6\ISCC.exe')
$onPath = Get-Command ISCC.exe -ErrorAction SilentlyContinue
if ($onPath) { $candidates += $onPath.Source }
foreach ($base in @(${env:ProgramFiles(x86)}, $env:ProgramFiles, (Join-Path $env:LOCALAPPDATA 'Programs'))) {
if ($base) {
$candidates += (Join-Path $base 'Inno Setup 6\ISCC.exe')
$candidates += (Join-Path $base 'Inno Setup 7\ISCC.exe')
}
}
foreach ($candidate in $candidates) {
if (Test-Path -LiteralPath $candidate -PathType Leaf) { return $candidate }
}
Write-Host '[2/5] Downloading the official Inno Setup 6.7.3 compiler (first build only)...'
$toolsDir = Join-Path $PSScriptRoot '.tools'
New-Item -ItemType Directory -Force -Path $toolsDir | Out-Null
$setupPath = Join-Path $toolsDir 'innosetup-6.7.3.exe'
if (-not (Test-Path -LiteralPath $setupPath)) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -UseBasicParsing -Uri 'https://github.com/jrsoftware/issrc/releases/download/is-6_7_3/innosetup-6.7.3.exe' -OutFile ($setupPath + '.download')
Move-Item -LiteralPath ($setupPath + '.download') -Destination $setupPath -Force
}
$signature = Get-AuthenticodeSignature -LiteralPath $setupPath
if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'Pyrsys B\.V\.') {
throw "Inno Setup publisher signature could not be verified. Remove $setupPath and retry, or set MDHELPER_ISCC to an installed compiler."
}
$innoDir = Join-Path $toolsDir 'InnoSetup6'
$arguments = @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-', '/CURRENTUSER', '/NOICONS', '/TASKS=', ('/DIR="' + $innoDir + '"'))
$process = Start-Process -FilePath $setupPath -ArgumentList $arguments -Wait -PassThru -WindowStyle Hidden
if ($process.ExitCode -ne 0) { throw "Inno Setup installation failed: $($process.ExitCode)" }
$compiler = Join-Path $innoDir 'ISCC.exe'
if (-not (Test-Path -LiteralPath $compiler)) { throw 'Inno Setup compiler was not created.' }
return $compiler
}
try {
Push-Location $projectRoot
Write-Host '[1/5] Checking Python and build dependencies...'
$python = Find-Python
Write-Host "Python: $python"
# A system interpreter is used only to create an isolated build environment.
$isVenv = & $python -B -c 'import sys; print(int(sys.prefix != sys.base_prefix))'
if ($isVenv -ne '1') {
$venvRoot = Join-Path $PSScriptRoot '.venv'
Invoke-Checked $python @('-m', 'venv', $venvRoot)
$python = Join-Path $venvRoot 'Scripts\python.exe'
}
$probe = "import importlib.metadata as m, pathlib; lines=pathlib.Path('requirements.txt').read_text().splitlines(); assert all(m.version(n.strip()) == v.strip() for n,v in (s.split('==') for s in lines if '==' in s and not s.startswith('#')))"
if (-not (Test-PythonCode $python $probe)) {
Invoke-Checked $python @('-m', 'pip', 'install', '-r', 'requirements.txt')
}
if (-not (Test-Path -LiteralPath 'vendor\pandoc\pandoc.exe')) { throw 'Missing vendor\pandoc\pandoc.exe. Restore the bundled Pandoc before building.' }
$compiler = Find-InnoCompiler
Write-Host "Installer compiler: $compiler"
Write-Host '[3/5] Running regression tests...'
if (-not $SkipTests) {
if (-not (Test-PythonCode $python 'import pytest')) { Invoke-Checked $python @('-m', 'pip', 'install', 'pytest>=8,<10') }
Invoke-Checked $python @('-B', '-m', 'pytest', '-q', 'tests')
} else { Write-Host 'Tests explicitly skipped.' }
Write-Host '[4/5] Building the application directory...'
# Exclude unrelated tool runtimes from native DLL resolution.
$env:PATH = (($env:PATH -split ';') | Where-Object { $_ -notmatch '\\codex-runtimes\\' }) -join ';'
Invoke-Checked $python @('-m', 'PyInstaller', '--noconfirm', '--clean', 'MDHelper.spec')
$appPath = Join-Path $projectRoot 'dist\MDHelper\MDHelper.exe'
if (-not (Test-Path -LiteralPath $appPath)) { throw 'The application directory was not generated.' }
Write-Host '[5/5] Compiling the installer...'
$version = (& $python -B -c 'from mdhelper import __version__; print(__version__)').Trim()
if ($version -notmatch '^\d+\.\d+\.\d+([.-][A-Za-z0-9.]+)?$') { throw "Invalid application version: $version" }
Invoke-Checked $compiler @('/Qp', "/DAppVersion=$version", "/DSourceRoot=$projectRoot", (Join-Path $PSScriptRoot 'MDHelper.iss'))
$installer = Join-Path $PSScriptRoot "output\MDHelper-Setup-$version-x64.exe"
if (-not (Test-Path -LiteralPath $installer)) { throw 'The installer was not generated.' }
$hash = (Get-FileHash -LiteralPath $installer -Algorithm SHA256).Hash.ToLowerInvariant()
Set-Content -LiteralPath ($installer + '.sha256') -Value ($hash + ' ' + (Split-Path -Leaf $installer)) -Encoding ASCII
Write-Host "SUCCESS: $installer" -ForegroundColor Green
Write-Host "Build log: $logFile"
} catch {
Write-Host "BUILD FAILED: $($_.Exception.Message)" -ForegroundColor Red
exit 1
} finally {
Pop-Location
Stop-Transcript | Out-Null
}