81 lines
8.5 KiB
PowerShell

[CmdletBinding()]
param([string]$CertificateThumbprint,[switch]$NoSync)
$ErrorActionPreference='Stop'
if($env:OS -ne 'Windows_NT'){throw 'Run this command on Windows. It never installs the add-in.'}
. (Join-Path $PSScriptRoot 'DeveloperPackage.ps1')
$repo=(Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
Push-Location $repo
try {
$sharedBranch='codex/word-companion-native-phase1-20261104'
$branch=(& git branch --show-current).Trim();if($LASTEXITCODE -ne 0 -or $branch -ne $sharedBranch){throw "Use the existing shared branch $sharedBranch. No branch was switched."}
$dirty=& git status --porcelain=v1;if($LASTEXITCODE -ne 0){throw 'Cannot inspect Git status.'}
if($dirty){throw 'Working tree has local changes. Preserve/commit them before updating; nothing was discarded.'}
$scriptHash=(Get-FileHash -Algorithm SHA256 -LiteralPath $PSCommandPath).Hash
$remote=(& git config --get "branch.$sharedBranch.remote").Trim()
if($LASTEXITCODE -ne 0 -or !$remote -or $remote -eq '.'){throw 'The shared branch must have an external tracking remote configured. No remote was guessed.'}
if($NoSync){
# Build a clean local qualification commit after the caller has safely fetched.
# Local packaging fixes must be tested before publication, not pushed to pass this gate.
Invoke-Checked git @('merge-base','--is-ancestor',"$remote/$sharedBranch",'HEAD')
}else{
Invoke-Checked git @('fetch',$remote)
$ahead=(& git rev-list --left-right --count "HEAD...$remote/$sharedBranch") -split '\s+'
if($LASTEXITCODE -ne 0 -or [int]$ahead[0] -gt 0){throw 'Local commits are not on the shared remote branch. Push/reconcile them safely before updating.'}
Invoke-Checked git @('merge','--ff-only',"$remote/$sharedBranch")
}
if((Get-FileHash -Algorithm SHA256 -LiteralPath $PSCommandPath).Hash -ne $scriptHash){& $PSCommandPath @PSBoundParameters;return}
Invoke-Checked git @('merge-base','--is-ancestor','726a3d5','HEAD')
$commit=(& git rev-parse HEAD).Trim();if($LASTEXITCODE -ne 0){throw 'Cannot read commit SHA.'}
$version=([xml](Get-Content -Raw 'PlotDirector.NativeCompanion\DeveloperVersion.props')).Project.PropertyGroup.ApplicationVersion
$output=Join-Path (Get-DownloadsFolder) "PlotDirectorWordCompanion\$version-$($commit.Substring(0,8))"
if(Test-Path -LiteralPath $output){$existing=Test-DeveloperPackage $output;Write-Output "Verified existing package $($existing.version), SHA $($existing.commit): $output";return}
$settings=Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'PlotDirector\CompanionDeveloper\build-settings.json'
if(!$CertificateThumbprint -and (Test-Path -LiteralPath $settings)){$CertificateThumbprint=(Get-Content -Raw $settings|ConvertFrom-Json).certificateThumbprint}
if(!$CertificateThumbprint){$CertificateThumbprint=Get-InstalledSigningThumbprint}
if(!$CertificateThumbprint){
$candidates=@(Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Where-Object {$_.HasPrivateKey -and $_.NotAfter -gt (Get-Date) -and $_.NotBefore -lt (Get-Date)})
if($candidates.Count -ne 1){throw 'Specify -CertificateThumbprint for your existing developer code-signing certificate. It is remembered for future builds; no new certificate or trust-store change is made.'}
$CertificateThumbprint=$candidates[0].Thumbprint
}
$cert=Get-Item "Cert:\CurrentUser\My\$CertificateThumbprint"
if(!$cert.HasPrivateKey -or $cert.NotAfter -le (Get-Date)){throw 'The signing certificate is missing its private key or is expired.'}
$vswhere=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
if(!(Test-Path -LiteralPath $vswhere)){throw 'vswhere is missing. Existing Visual Studio Office tools are required. No installer will be launched.'}
$msbuild=& $vswhere -latest -requires Microsoft.VisualStudio.Workload.Office -find 'MSBuild\**\Bin\amd64\MSBuild.exe' | Select-Object -First 1
if(!$msbuild){throw 'Office-equipped MSBuild was not found. No workloads or IDE settings were changed.'}
$desktopRuntime=& dotnet --list-runtimes
if($LASTEXITCODE -ne 0 -or !($desktopRuntime -match '^Microsoft.WindowsDesktop.App 10\.')){throw 'The .NET 10 Windows Desktop runtime is required for the tray Companion. No runtime or Visual Studio installation was attempted.'}
Invoke-Checked dotnet @('build','PlotLine.slnx','-c','Release','--disable-build-servers','-m:1','/p:UseSharedCompilation=false')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion-http')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-workflow')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-tray')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-import')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--intent-assessment')
# Office Clean unregisters the installed add-in. Build signed outputs without that target or F5 registration.
Invoke-Checked $msbuild @('PlotDirector.NativeCompanion\Vsto\PlotDirector.WordAddIn.csproj','/restore','/t:Build;VisualStudioForApplicationsBuild','/p:Configuration=Release','/p:PrepareForRunDependsOn=CopyFilesToOutputDirectory','/p:SignManifests=true',"/p:ManifestCertificateThumbprint=$CertificateThumbprint","/p:ApplicationVersion=$version")
$bin=Join-Path $repo 'PlotDirector.NativeCompanion\Vsto\bin\Release'
# Office's development-manifest target substitutes AssemblyName as publisher.
# Set the existing release publisher without changing the product identity,
# recompute the application-manifest digest with SHA256, then re-sign normally.
$mage=Join-Path ${env:ProgramFiles(x86)} 'Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\mage.exe'
if(!(Test-Path $mage)){throw 'Existing SDK mage was not found. No SDK was installed.'}
Invoke-Checked $mage @('-Update',(Join-Path $bin 'PlotDirector.WordAddIn.vsto'),'-AppManifest',(Join-Path $bin 'PlotDirector.WordAddIn.dll.manifest'),'-Publisher','Nick Beckley','-Algorithm','sha256RSA')
Invoke-Checked $mage @('-Sign',(Join-Path $bin 'PlotDirector.WordAddIn.vsto'),'-CertHash',$CertificateThumbprint,'-Algorithm','sha256RSA')
$staging=$output+'.preparing-'+[guid]::NewGuid().ToString('N')
New-Item -ItemType Directory -Path $staging -Force | Out-Null
Copy-Item -Path (Join-Path $bin '*') -Destination $staging -Recurse
Invoke-Checked dotnet @('publish','PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj','-f','net10.0-windows10.0.19041.0','-c','Release','-r','win-x64','--self-contained','false','-o',(Join-Path $staging 'Agent'))
if((& git rev-parse HEAD).Trim() -ne $commit){throw 'Git HEAD changed during the build. No package was installed; rerun after the repository is stable.'}
if(& git status --porcelain=v1){throw 'Build generated source changes; review them before packaging. No installation was changed.'}
$files=@(Get-ChildItem -LiteralPath $staging -Recurse -File | ForEach-Object { @{path=$_.FullName.Substring($staging.Length+1).Replace('\','/');sha256=(Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash} })
@{version=$version;commit=$commit;publisher='Nick Beckley';certificateThumbprint=$CertificateThumbprint;createdUtc=[DateTime]::UtcNow.ToString('O');files=$files} | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $staging 'package.json') -Encoding UTF8
$null=Test-DeveloperPackage $staging
Move-Item -LiteralPath $staging -Destination $output
New-Item -ItemType Directory -Path (Split-Path $settings) -Force | Out-Null
@{certificateThumbprint=$CertificateThumbprint} | ConvertTo-Json | Set-Content -LiteralPath $settings -Encoding UTF8
Write-Output "Build and tests passed. Version: $version; Git SHA: $commit; Package: $output"
Write-Output "Not installed. Prepare the unified EXE/MSI with Setup\Build-Setup.ps1. Installation and Word acceptance require a separately authorised interactive window."
} finally {Pop-Location}