Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

wezterm/tests/quake_portability_test.ps1

Raw
# No desktop input or GUI launch; fixtures live under OS temp and are removed.
$ErrorActionPreference = 'Stop'
$source = Join-Path $PSScriptRoot '../quake/quake.ps1'
$pwsh = Join-Path $PSHOME 'pwsh.exe'
$wezterm = (Get-Command wezterm.exe -CommandType Application).Source
$gui = Join-Path (Split-Path $wezterm) 'wezterm-gui.exe'
$root = Join-Path ([IO.Path]::GetTempPath()) ('quake-portability-' + [guid]::NewGuid())
$copy = Join-Path $root "Fresh user Ω's files/quake"
[void][IO.Directory]::CreateDirectory($copy)
Copy-Item $source $copy
$script = Join-Path $copy 'quake.ps1'
function Assert($condition, $message) { if (-not $condition) { throw $message } }
function Run([string]$executable, [string[]]$arguments, [hashtable]$environment = @{}) {
    $info = [Diagnostics.ProcessStartInfo]::new($executable)
    $info.UseShellExecute = $false
    $info.CreateNoWindow = $true
    $info.RedirectStandardOutput = $true
    $info.RedirectStandardError = $true
    $info.WorkingDirectory = $root
    foreach ($argument in $arguments) { $info.ArgumentList.Add($argument) }
    foreach ($key in $environment.Keys) { $info.Environment[$key] = $environment[$key] }
    $process = [Diagnostics.Process]::Start($info)
    try {
        $stdout = $process.StandardOutput.ReadToEndAsync()
        $stderr = $process.StandardError.ReadToEndAsync()
        if (-not $process.WaitForExit(30000)) { $process.Kill(); throw 'Portability child timed out.' }
        [pscustomobject]@{ code=$process.ExitCode; output=$stdout.GetAwaiter().GetResult() + $stderr.GetAwaiter().GetResult() }
    } finally { $process.Dispose() }
}
function IsShimRejection($result) {
    if ($result.code -eq 0) { return $false }
    foreach ($component in @('launcher shim', '-WezTermPath', 'real installed', 'wezterm-gui.exe')) {
        if (-not $result.output.Contains($component)) { return $false }
    }
    return $true
}
$controllerStarted = $false
try {
    $result = Run $pwsh @('-NoProfile', '-NonInteractive', '-File', $script, '-Background', '-WezTermPath', (Join-Path $root 'missing/wezterm-gui.exe'))
    Assert ($result.code -ne 0 -and $result.output.Contains('WezTerm GUI not found')) 'Missing explicit executable did not produce actionable error before background launch.'
    $cleanEnvironment = @{ PATH=(Join-Path $root 'no-tools'); ProgramFiles=(Join-Path $root 'no-program-files'); 'ProgramFiles(x86)'=(Join-Path $root 'no-program-files-x86') }
    # Simulate absent WezTerm at the command/filesystem discovery boundary; real installs stay untouched.
    $missingHarness = Join-Path $root 'missing-wezterm.ps1'
    $quotedScript = $script.Replace("'", "''")
    Set-Content -LiteralPath $missingHarness -Value @"
function Get-Command { param([string]`$Name, [string]`$CommandType) if (`$Name -in @('wezterm.exe', 'wezterm-gui.exe')) { return }; Microsoft.PowerShell.Core\Get-Command -Name `$Name -CommandType `$CommandType }
function Test-Path { param([string]`$LiteralPath, [string]`$PathType) if ([IO.Path]::GetFileName(`$LiteralPath) -eq 'wezterm-gui.exe') { return `$false }; Microsoft.PowerShell.Management\Test-Path -LiteralPath `$LiteralPath -PathType `$PathType }
& '$quotedScript' -Background
"@
    $result = Run $pwsh @('-NoProfile', '-NonInteractive', '-File', $missingHarness) $cleanEnvironment
    Assert ($result.code -ne 0 -and $result.output.Contains('WezTerm is not installed or could not be found') -and $result.output.Contains('-WezTermPath')) "Absent WezTerm diagnostic failed: $($result.output)"
    # Discovery-only fixture: never execute this empty binary.
    $portableExe = Join-Path $copy 'wezterm-gui.exe'
    [IO.File]::WriteAllBytes($portableExe, [byte[]]@())
    $result = Run $pwsh @('-NoProfile', '-NonInteractive', '-File', $script, '-Check') $cleanEnvironment
    Assert ($result.code -eq 0) "Colocated portable discovery failed: $($result.output)"
    $shim = [IO.Path]::ChangeExtension($portableExe, '.shim')
    Set-Content -LiteralPath $shim -Value ('path = "' + $gui + '"')
    $result = Run $pwsh @('-NoProfile', '-NonInteractive', '-File', $script, '-Background') $cleanEnvironment
    Assert (IsShimRejection $result) "Shim rejection failed: $($result.output)"
    foreach ($component in @('launcher shim', '-WezTermPath', 'real installed', 'wezterm-gui.exe')) {
        $incomplete = [pscustomobject]@{ code=1; output='launcher shim; -WezTermPath; real installed; wezterm-gui.exe'.Replace($component, '') }
        Assert (-not (IsShimRejection $incomplete)) "Shim assertion accepted diagnostic missing '$component'."
    }
    Remove-Item -LiteralPath $shim
    $normalConfig = Join-Path $copy 'normal config.lua'
    Set-Content -LiteralPath $normalConfig -Value "return { keys = {{ key = 'F8', mods = 'CTRL', action = require('wezterm').action.Nop }} }"
    $relativeHarness = Join-Path $root 'relative-paths.ps1'
    Set-Content -LiteralPath $relativeHarness -Value ("Set-Location -LiteralPath '" + $copy.Replace("'", "''") + "'; & '" + $quotedScript + "' -Check -WezTermPath './wezterm-gui.exe' -ConfigFile './normal config.lua'")
    $result = Run $pwsh @('-NoProfile', '-NonInteractive', '-File', $relativeHarness)
    Assert ($result.code -eq 0) "Relative paths ignored PowerShell location: $($result.output)"
    Remove-Item -LiteralPath $portableExe
    $result = Run powershell.exe @('-NoProfile', '-NonInteractive', '-File', $script, '-Check')
    Assert ($result.code -ne 0 -and $result.output.Contains('requires PowerShell 7')) 'Windows PowerShell 5.1 did not explain PowerShell 7 requirement.'
    $result = Run $pwsh @('-NoProfile', '-NonInteractive', '-File', $script, '-Background', '-WezTermPath', $gui, '-ConfigFile', (Join-Path $root 'absent.lua'))
    Assert ($result.code -ne 0 -and $result.output.Contains('WezTerm config file not found')) 'Missing explicit config did not fail before hidden launch.'
    $taskBefore = Get-ScheduledTask -TaskName 'WezTerm Quake Prototype' -TaskPath '\' -ErrorAction SilentlyContinue
    Assert (-not $taskBefore) 'Task preview test requires no preexisting prototype task.'
    $result = Run $pwsh @('-NoProfile', '-NonInteractive', '-File', $script, '-InstallTask', '-WhatIf', '-WezTermPath', $gui, '-ConfigFile', $normalConfig)
    Assert ($result.code -eq 0) "Task construction/preview failed: $($result.output)"
    Assert (-not (Get-ScheduledTask -TaskName 'WezTerm Quake Prototype' -TaskPath '\' -ErrorAction SilentlyContinue)) 'Task preview changed Scheduler.'

    # Check the same ProcessStartInfo used for a real launch, then pass its global args
    # to installed WezTerm's read-only show-keys command. Native discovery replaces our Lua loader.
    $launchHarness = Join-Path $root 'verify-launch.ps1'
    $quotedGui = $gui.Replace("'", "''")
    Set-Content -LiteralPath $launchHarness -Value @'
param([string]$Launcher, [string]$Gui, [string]$Cli, [string]$NormalConfig, [switch]$Explicit)
$ErrorActionPreference = 'Stop'
$params = @{ Check=$true; WezTermPath=$Gui }
if ($Explicit) { $params.ConfigFile=$NormalConfig }
$diagnostic = & $Launcher @params
$start = [QuakePrototype]::StartInfo()
$arguments = @($start.ArgumentList)
foreach ($required in @('--always-new-process', '--no-auto-connect', '--class', '--domain', 'local')) {
    if ($arguments -notcontains $required) { throw "Missing isolation argument $required" }
}
$startIndex = [Array]::IndexOf($arguments, 'start')
if ($startIndex -lt 1) { throw 'Missing native start command' }
foreach ($override in @('use_resize_increments=false', "default_workspace='quake'", "window_close_confirmation='AlwaysPrompt'")) {
    $index = [Array]::IndexOf($arguments, $override)
    if ($index -lt 1 -or $index -ge $startIndex -or $arguments[$index-1] -ne '--config') { throw "Missing global override $override" }
}
if ($Explicit) {
    if ($arguments[0] -ne '--config-file' -or $arguments[1] -ne $NormalConfig) { throw 'Explicit config path lost' }
} elseif ($arguments -contains '--config-file') { throw 'Default launch must use native discovery' }
if ($start.Environment['WEZTERM_CONFIG_FILE'] -ne $env:WEZTERM_CONFIG_FILE) { throw 'Native config environment lost' }
foreach ($removed in @('WEZTERM_UNIX_SOCKET', 'WEZTERM_PANE', 'WEZTERM_QUAKE_CONFIG')) {
    if ($start.Environment.ContainsKey($removed)) { throw "Inherited routing/adapter state leaked: $removed" }
}
$output = & $Cli @($arguments[0..($startIndex-1)]) show-keys 2>&1 | Out-String
if ($LASTEXITCODE -ne 0 -or $output.Contains('ERROR') -or -not $output.Contains('F8')) { throw "Native config/CLI overrides failed: $output" }
'PASS native invocation'
'@
    $nativeEnvironment = @{ WEZTERM_CONFIG_FILE=$normalConfig; WEZTERM_UNIX_SOCKET='unrelated-test-socket'; WEZTERM_PANE='999'; WEZTERM_QUAKE_CONFIG='obsolete-adapter-state' }
    foreach ($explicit in @($false, $true)) {
        $arguments = @('-NoProfile', '-NonInteractive', '-File', $launchHarness, '-Launcher', $script, '-Gui', $gui, '-Cli', $wezterm, '-NormalConfig', $normalConfig)
        if ($explicit) { $arguments += '-Explicit' }
        $result = Run $pwsh $arguments $nativeEnvironment
        Assert ($result.code -eq 0) "Native invocation (explicit=$explicit) failed: $($result.output)"
    }
    # Single-file background lifecycle from relocated directory; never send a toggle.
    $result = Run $pwsh @('-NoProfile', '-NonInteractive', '-File', $script, '-Background', '-WezTermPath', $gui)
    Assert ($result.code -eq 0) "Relocated background start failed: $($result.output)"
    $controllerStarted = $true
    $deadline = (Get-Date).AddSeconds(15)
    $ready = $false
    while ((Get-Date) -lt $deadline) {
        try { $event = [Threading.EventWaitHandle]::OpenExisting('Local\bugabinga.wezterm-quake.prototype.stop'); $event.Dispose(); $ready = $true; break }
        catch { Start-Sleep -Milliseconds 100 }
    }
    Assert $ready 'Relocated hidden controller did not become ready.'
    $result = Run $pwsh @('-NoProfile', '-NonInteractive', '-File', $script, '-Stop')
    Assert ($result.code -eq 0) 'Relocated controller stop failed.'
    $deadline = (Get-Date).AddSeconds(10)
    do {
        $alive = $false
        try { $event = [Threading.EventWaitHandle]::OpenExisting('Local\bugabinga.wezterm-quake.prototype.stop'); $event.Dispose(); $alive = $true; Start-Sleep -Milliseconds 100 } catch { }
    } while ($alive -and (Get-Date) -lt $deadline)
    Assert (-not $alive) 'Relocated controller did not release hotkeys/event.'
    $controllerStarted = $false
    'PASS: single-file relocation/relative paths; dependency/shim errors; task preview; native config selection/CLI overrides; mux environment isolation; hidden controller lifecycle (no GUI).'
} catch {
    Write-Output "FAIL: $_"
    throw
} finally {
    if ($controllerStarted) { & $script -Stop }
    for ($attempt = 0; $attempt -lt 10; $attempt++) {
        try { Remove-Item -LiteralPath $root -Recurse -Force; break }
        catch { if ($attempt -eq 9) { Write-Warning "Fixture cleanup failed: $root ($_)" }; Start-Sleep -Milliseconds 200 }
    }
}