From f92a3460cd5a95a4d7b5696dda77dad86ffd4eab Mon Sep 17 00:00:00 2001 From: Calmy Jane Date: Sun, 25 Oct 2026 21:35:56 +0400 Subject: [PATCH 1/9] Close only the job's own LabVIEWs, and none with unsaved changes Resolve-CiEnvironment.ps1 -Fix -CleanStart passed every installed LabVIEW to Stop-LeftoverVipm. Whenever a VIPM Desktop was open at the start of a job, every running LabVIEW on the machine was force-closed, including the maintainer's development LabVIEW on the runner machine, with whatever was unsaved in it. Now the clean start runs after the test and comparison LabVIEWs have been chosen and only ever closes those two. Of these, a LabVIEW one of whose windows has a "*" in its title (LabVIEW's mark for unsaved changes) is left running, with a note in the job summary, unless the runner's environment has CI_DEDICATED_MACHINE=1. The same rule applies where else CI force-closes a LabVIEW: closing the test LabVIEW at the clean start, and Resolve-ViServerPort -Fix closing a LabVIEW that does not listen on its port (which Invoke-CliTest.ps1 and New-ViDiffReport.ps1 also call). When that LabVIEW is kept, its LabVIEW.ini is not written while it runs, and the compiled object cache of a test LabVIEW that is still running is kept. New functions in LabVIEWCi.psm1: Select-LabVIEWToStop (the decision, with no side effects), Get-ProcessWindowTitle (titles of all visible top-level windows of a process), Get-RunningLabVIEW, Stop-CiLabVIEW and Test-CiDedicatedMachine. The doc comments now say that these LabVIEWs are force-closed. tools/setup/README.md documents CI_DEDICATED_MACHINE. A test or comparison LabVIEW without unsaved changes is still closed, and VIPM Desktop is still ended at the clean start; unsaved changes in a VI whose window is not open cannot be seen from outside. Co-Authored-By: Claude Opus 5.5 --- tools/ci/LabVIEWCi.psm1 | 172 ++++++++++++++++++++++++++--- tools/ci/Resolve-CiEnvironment.ps1 | 93 +++++++++------- tools/setup/README.md | 12 ++ 3 files changed, 222 insertions(+), 55 deletions(-) diff --git a/tools/ci/LabVIEWCi.psm1 b/tools/ci/LabVIEWCi.psm1 index 3dae63d..757f5e0 100644 --- a/tools/ci/LabVIEWCi.psm1 +++ b/tools/ci/LabVIEWCi.psm1 @@ -112,6 +112,116 @@ function Get-LabVIEWProcess([string]$Path) { Where-Object { $_.Path -and ($_.Path -ieq $Path) } | Select-Object -First 1 } +function Test-CiDedicatedMachine { + <# True when the environment variable CI_DEDICATED_MACHINE is 1: nobody + works on this machine, so a LabVIEW with unsaved changes may be closed + as well (see Select-LabVIEWToStop). #> + return ("$env:CI_DEDICATED_MACHINE" -eq '1') +} + +function Get-ProcessWindowTitle { + <# Titles of the visible top-level windows of a process: every front + panel, block diagram and project window of a LabVIEW, not only the one + Process.MainWindowTitle reports. Falls back to MainWindowTitle when the + window list cannot be read. Read-only. #> + param([Parameter(Mandatory = $true)][int]$ProcessId) + try { + if (-not ('LabVIEWCi.Windows' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +namespace LabVIEWCi { + public static class Windows { + delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); + [DllImport("user32.dll")] static extern bool EnumWindows(EnumWindowsProc callback, IntPtr lParam); + [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId); + [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr hWnd); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowTextLength(IntPtr hWnd); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxCount); + public static string[] Titles(int processId) { + List titles = new List(); + EnumWindows(delegate (IntPtr hWnd, IntPtr lParam) { + uint owner; + GetWindowThreadProcessId(hWnd, out owner); + if (owner == (uint)processId && IsWindowVisible(hWnd)) { + int length = GetWindowTextLength(hWnd); + if (length > 0) { + StringBuilder text = new StringBuilder(length + 1); + GetWindowText(hWnd, text, text.Capacity); + titles.Add(text.ToString()); + } + } + return true; + }, IntPtr.Zero); + return titles.ToArray(); + } + } +} +'@ + } + return @([LabVIEWCi.Windows]::Titles($ProcessId)) + } catch { + $title = (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue).MainWindowTitle + if ($title) { return @($title) } else { return @() } + } +} + +function Select-LabVIEWToStop { + <# Decides which running LabVIEWs a CI step may end. Changes nothing. + Process: objects with Id, Path and WindowTitles (Get-RunningLabVIEW). + LabVIEWPath: the LabVIEWs this job uses (tests/build and comparison). + Returns one object per process with Id, Path, Stop and Reason: + * a LabVIEW at any other path is never stopped: on a developer + machine that is where someone works; + * a LabVIEW one of whose windows has a title with "*", which LabVIEW + shows for unsaved changes, is not stopped either, unless Dedicated + is set (CI_DEDICATED_MACHINE=1, nobody works on this machine); + * every other LabVIEW at one of the LabVIEWPath paths is stopped. #> + param([object[]]$Process = @(), [string[]]$LabVIEWPath = @(), [switch]$Dedicated) + $wanted = @($LabVIEWPath | Where-Object { $_ }) + foreach ($p in @($Process | Where-Object { $_ })) { + $path = "$($p.Path)" + $used = [bool](@($wanted | Where-Object { $_ -ieq $path }).Count) + $unsaved = @($p.WindowTitles | Where-Object { "$_" -match '\*' }) + if (-not $used) { + $stop = $false; $reason = 'not a LabVIEW this job uses' + } elseif ($unsaved.Count -gt 0 -and -not $Dedicated) { + $stop = $false + $reason = "it has unsaved changes (window ""$($unsaved[0])""); save or close them, or set CI_DEDICATED_MACHINE=1 on a machine nobody works on" + } else { + $stop = $true; $reason = if ($unsaved.Count -gt 0) { 'CI_DEDICATED_MACHINE=1, unsaved changes are discarded' } else { 'used by this job' } + } + [pscustomobject]@{ Id = $p.Id; Path = $path; Stop = $stop; Reason = $reason } + } +} + +function Get-RunningLabVIEW { + <# The running LabVIEW processes at the given paths, with the titles of + their windows, as Select-LabVIEWToStop takes them. Read-only. #> + param([string[]]$LabVIEWPath = @()) + foreach ($path in @($LabVIEWPath | Where-Object { $_ } | Select-Object -Unique)) { + $process = Get-LabVIEWProcess $path + if (-not $process) { continue } + [pscustomobject]@{ Id = $process.Id; Path = $process.Path; WindowTitles = @(Get-ProcessWindowTitle $process.Id) } + } +} + +function Stop-CiLabVIEW { + <# Ends the running LabVIEWs at LabVIEWPath that Select-LabVIEWToStop + allows to end, and waits up to 60 s for each. Returns the decisions + (Id, Path, Stop, Reason), so the caller can say what it ended and what + it left running. #> + param([string[]]$LabVIEWPath = @()) + $decisions = @(Select-LabVIEWToStop -Process @(Get-RunningLabVIEW $LabVIEWPath) -LabVIEWPath $LabVIEWPath -Dedicated:(Test-CiDedicatedMachine)) + foreach ($d in $decisions | Where-Object { $_.Stop }) { + Stop-Process -Id $d.Id -Force -ErrorAction SilentlyContinue + Wait-Process -Id $d.Id -Timeout 60 -ErrorAction SilentlyContinue + } + return $decisions +} + function Get-VipmPort { <# The VI Server port VIPM has recorded for the LabVIEW at Path, or 0. Read-only. VIPM keeps its LabVIEW list in the [Targets] section of its @@ -150,9 +260,13 @@ function Resolve-ViServerPort { With -Fix it repairs what is easy to repair: VI Server disabled or on a different port in LabVIEW.ini, a port taken by another program or configured for another LabVIEW (Avoid), and an instance that runs on a - different port or none (it is closed so that LabVIEW CLI starts it again - with the settings written here). Without -Fix it only reports, and uses a - running instance's port as it is. + different port or none: that LabVIEW is force-closed (Stop-Process, + unsaved changes are lost) so that LabVIEW CLI starts it again with the + settings written here. A running instance with unsaved changes (a window + title with "*") is not closed unless CI_DEDICATED_MACHINE=1; it is then + handled as without -Fix, and LabVIEW.ini is not written while it runs. + Without -Fix it only reports, and uses a running instance's port as it + is when that is its LabVIEW.ini port or the requested port. #> param( [Parameter(Mandatory = $true)][string]$Path, @@ -172,6 +286,9 @@ function Resolve-ViServerPort { $notes.Add("VIPM's port $Preferred for this LabVIEW is also used by another LabVIEW; set different ports in VIPM (Tools > Options > LabVIEW).") } + # LabVIEW.ini is only written when -Fix is given and this LabVIEW is not + # running: LabVIEW rewrites the file when it exits. + $write = [bool]$Fix $process = Get-LabVIEWProcess $Path if ($process) { $listening = Get-ListeningPort $process.Id @@ -180,16 +297,27 @@ function Resolve-ViServerPort { return [pscustomobject]@{ Port = $want; Notes = $notes; Changed = $false } } $actual = @($iniPort, $Requested) | Where-Object { $_ -and ($listening -contains $_) } | Select-Object -First 1 + $was = if ($actual) { "on port $actual" } else { 'without listening on its VI Server port' } + $stop = $null if ($Fix) { - $was = if ($actual) { "on port $actual" } else { 'without listening on its VI Server port' } - $notes.Add("LabVIEW (process $($process.Id)) was running $was instead of on $want; closed it so LabVIEW CLI starts it with the settings below.") + $titles = @(Get-ProcessWindowTitle $process.Id) + $stop = Select-LabVIEWToStop -Process @([pscustomobject]@{ Id = $process.Id; Path = $Path; WindowTitles = $titles }) -LabVIEWPath @($Path) -Dedicated:(Test-CiDedicatedMachine) + if (-not $stop.Stop) { + $notes.Add("LabVIEW (process $($process.Id)) runs $was instead of on $want, but was not closed: $($stop.Reason).") + $write = $false + } + } + if ($stop -and $stop.Stop) { + $notes.Add("LabVIEW (process $($process.Id)) was running $was instead of on $want; force-closed it so LabVIEW CLI starts it with the settings below.") Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue Wait-Process -Id $process.Id -Timeout 60 -ErrorAction SilentlyContinue } elseif ($actual) { - $notes.Add("LabVIEW (process $($process.Id)) runs on port $actual, not on $want (VIPM may move it back); using $actual. Run with -Fix to repair it.") + $hint = if ($Fix) { 'It is repaired once it can be closed.' } else { 'Run with -Fix to repair it.' } + $notes.Add("LabVIEW (process $($process.Id)) runs on port $actual, not on $want (VIPM may move it back); using $actual. $hint") return [pscustomobject]@{ Port = $actual; Notes = $notes; Changed = $false } } else { - $notes.Add("LabVIEW (process $($process.Id)) is running but not listening on its VI Server port ($iniPort); LabVIEW CLI will probably not reach it. Close it, or run with -Fix.") + $hint = if ($Fix) { 'Close it.' } else { 'Close it, or run with -Fix.' } + $notes.Add("LabVIEW (process $($process.Id)) is running but not listening on its VI Server port ($iniPort); LabVIEW CLI will probably not reach it. $hint") } } @@ -212,7 +340,7 @@ function Resolve-ViServerPort { $changed = $false if ($changes.Count -gt 0) { $list = ($changes.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join ', ' - if ($Fix) { + if ($write) { try { foreach ($entry in $changes.GetEnumerator()) { Set-IniValue $ini $entry.Key $entry.Value } $notes.Add("Set $list in $ini.") @@ -220,6 +348,8 @@ function Resolve-ViServerPort { } catch { $notes.Add("Could not write $ini ($($_.Exception.Message)); it needs $list.") } + } elseif ($Fix) { + $notes.Add("$ini needs $list; not written while this LabVIEW runs.") } else { $notes.Add("$ini needs $list (run with -Fix to write it).") } @@ -232,20 +362,25 @@ function Stop-LeftoverVipm { <# Ends a running VIPM Desktop and, only if one was running, the LabVIEWs at LabVIEWPath it may have been driving. For the start of a CI job, where a running VIPM Desktop belongs to an earlier job (see - Resolve-CiEnvironment.ps1, -CleanStart). Returns a note, or nothing - when VIPM Desktop was not running. #> + Resolve-CiEnvironment.ps1, -CleanStart). LabVIEWPath must be the + LabVIEWs the job uses, not every installed one: LabVIEWs at other + paths are never touched, and of these only those without unsaved + changes are ended (see Select-LabVIEWToStop, CI_DEDICATED_MACHINE). + Both are force-closed (Stop-Process). Returns notes, or nothing when + VIPM Desktop was not running. #> param([string[]]$LabVIEWPath = @(), [string]$ProcessName = 'VI Package Manager') $desktop = @(Get-Process -Name $ProcessName -ErrorAction SilentlyContinue) if ($desktop.Count -eq 0) { return } - $driven = @($LabVIEWPath | ForEach-Object { Get-LabVIEWProcess $_ } | Where-Object { $_ }) - # Read the paths first: a stopped process no longer reports one. - $drivenPaths = @($driven | ForEach-Object { $_.Path }) - $ended = @($desktop) + $driven - $ended | Stop-Process -Force -ErrorAction SilentlyContinue - $ended | ForEach-Object { Wait-Process -Id $_.Id -Timeout 60 -ErrorAction SilentlyContinue } + $desktop | Stop-Process -Force -ErrorAction SilentlyContinue + $desktop | ForEach-Object { Wait-Process -Id $_.Id -Timeout 60 -ErrorAction SilentlyContinue } + $decisions = @(Stop-CiLabVIEW -LabVIEWPath $LabVIEWPath) + $ended = @($decisions | Where-Object { $_.Stop }) $what = 'VIPM Desktop' - if ($driven.Count -gt 0) { $what += " and $($driven.Count) LabVIEW(s) ($($drivenPaths -join ', '))" } + if ($ended.Count -gt 0) { $what += " and $($ended.Count) LabVIEW(s) ($(($ended | ForEach-Object { $_.Path }) -join ', '))" } "Ended $what left over from an earlier job, so this job starts with a VIPM that answers." + foreach ($kept in $decisions | Where-Object { -not $_.Stop }) { + "Left LabVIEW $($kept.Path) (process $($kept.Id)) running: $($kept.Reason). VIPM may not answer if it was driving it." + } } function Find-Tool { @@ -275,4 +410,5 @@ function Get-LabVIEWCliPath { Export-ModuleMember -Function Get-LabVIEWInstall, Get-IniValue, Set-IniValue, Get-ListeningPort, Get-PortOwner, Get-FreePort, Get-LabVIEWProcess, Resolve-ViServerPort, Find-Tool, Get-LabVIEWCliPath, Get-ExeBitness, - Get-VipmPort, Stop-LeftoverVipm + Get-VipmPort, Stop-LeftoverVipm, Test-CiDedicatedMachine, Get-ProcessWindowTitle, Select-LabVIEWToStop, + Get-RunningLabVIEW, Stop-CiLabVIEW diff --git a/tools/ci/Resolve-CiEnvironment.ps1 b/tools/ci/Resolve-CiEnvironment.ps1 index 8fa8c08..81f37d4 100644 --- a/tools/ci/Resolve-CiEnvironment.ps1 +++ b/tools/ci/Resolve-CiEnvironment.ps1 @@ -24,28 +24,38 @@ are only used when LabVIEW.ini has none. LabVIEWCLI, vipm and gh are found on PATH or in their default folders. With -Fix it also: enables VI Server in LabVIEW.ini, moves a port that another -program holds, gives the two LabVIEWs different ports, closes a LabVIEW that -runs without listening on its port, and ends LabVIEW CLI processes left over -from a cancelled run. +program holds, gives the two LabVIEWs different ports, force-closes a test or +comparison LabVIEW that runs without listening on its port, and ends LabVIEW +CLI processes left over from a cancelled run. With -Fix -CleanStart (the first step of every job) it also ends a VIPM -Desktop left over from an earlier job, together with the running LabVIEWs it -may have been driving. A runner runs one job at a time, so a VIPM Desktop -that is running when a job starts belongs to an earlier one. When vipm gives -up on an operation, VIPM Desktop can carry on with it, or wait at a dialog, -long afterwards, and then never answers the next job ("wait for VIPM startup -timed out"). The vipm command line starts VIPM Desktop again when needed, and -LabVIEW CLI starts LabVIEW. It also closes the LabVIEW chosen for the tests -and the build if it is still running, and deletes that LabVIEW version's -compiled object cache (Documents\LabVIEW Data\VIObjCache\). The -repository's VIs are saved source-only, so their compiled code lives in that -cache, keyed by file path. Jobs of different pull requests use the same +Desktop left over from an earlier job, together with the running test and +comparison LabVIEWs it may have been driving. A runner runs one job at a +time, so a VIPM Desktop that is running when a job starts belongs to an +earlier one. When vipm gives up on an operation, VIPM Desktop can carry on +with it, or wait at a dialog, long afterwards, and then never answers the +next job ("wait for VIPM startup timed out"). The vipm command line starts +VIPM Desktop again when needed, and LabVIEW CLI starts LabVIEW. It also +force-closes the LabVIEW chosen for the tests and the build if it is still +running, and deletes that LabVIEW version's compiled object cache +(Documents\LabVIEW Data\VIObjCache\) unless that LabVIEW still runs. +The repository's VIs are saved source-only, so their compiled code lives in +that cache, keyed by file path. Jobs of different pull requests use the same workspace path, and a VI that is identical on both branches keeps its cache entry, compiled against the previous job's typedefs: the next build then looks for that job's files ("The following source VIs or Libraries are missing"). The check after the package install does not pass -CleanStart, so it keeps what the install just started. +Closing a LabVIEW (Stop-Process) discards whatever is open in it. So only the +test and comparison LabVIEWs chosen above are ever closed, never another +LabVIEW on the machine, and not one with unsaved changes (a window title with +"*"); such a LabVIEW is left running and the job summary says so. On a +machine nobody works on, set CI_DEDICATED_MACHINE=1 (an environment variable +of the runner, e.g. in its .env file) to close those as well. A test or +comparison LabVIEW without unsaved changes is closed even when someone has +it open: on a developer machine, do not work in the LabVIEWs CI uses. + The requested values come from the environment variables REQUESTED_LABVIEW_PATH, REQUESTED_LABVIEW_PORT, REQUESTED_COMPARE_PATH and REQUESTED_COMPARE_PORT (the workflows map the repository variables onto @@ -139,10 +149,6 @@ if ($installs.Count -eq 0) { } $usable = @($installs | Where-Object { $_.Year -ge $MinVersion }) -if ($Fix -and $CleanStart) { - Stop-LeftoverVipm -LabVIEWPath @($installs | ForEach-Object { $_.Path }) | ForEach-Object { $notes.Add($_) } -} - $test = $null if ($For -in 'Test', 'All' -and $installs.Count -gt 0) { $test = Select-Requested $env:REQUESTED_LABVIEW_PATH 'LABVIEW_PATH' $installs @@ -157,19 +163,44 @@ if ($For -in 'Test', 'All' -and $installs.Count -gt 0) { } } +$compare = $null +if ($For -in 'Compare', 'All' -and $installs.Count -gt 0) { + $compare = Select-Requested $env:REQUESTED_COMPARE_PATH 'LABVIEW_COMPARE_PATH' $installs + if (-not $compare) { + # Newest first; of the same version the 32-bit one. + $compare = $installs | Sort-Object @{ Expression = 'Year'; Descending = $true }, @{ Expression = { if ($_.Bitness -eq '32') { 0 } else { 1 } } } | Select-Object -First 1 + } + if ($compare -and $cliYear -and $compare.Year -lt $cliYear) { + $notes.Add("The comparison LabVIEW ($($compare.Year)) is older than LabVIEW CLI ($cliYear); its comparison operation will not load there.") + } +} + +# --- clean start ----------------------------------------------------------------- +# Only the LabVIEWs this job uses are closed, never any other LabVIEW on the +# machine, and none with unsaved changes unless CI_DEDICATED_MACHINE=1 (see +# Select-LabVIEWToStop in LabVIEWCi.psm1). +if ($Fix -and $CleanStart) { + $jobLabVIEWs = @(@($test, $compare) | Where-Object { $_ } | ForEach-Object { $_.Path } | Select-Object -Unique) + Stop-LeftoverVipm -LabVIEWPath $jobLabVIEWs | ForEach-Object { $notes.Add($_) } +} + if ($Fix -and $CleanStart -and $test) { # The previous job's VIs may still be loaded from the same workspace path. - $running = Get-LabVIEWProcess $test.Path - if ($running) { - $runningId = $running.Id - Stop-Process -Id $runningId -Force -ErrorAction SilentlyContinue - Wait-Process -Id $runningId -Timeout 60 -ErrorAction SilentlyContinue - $notes.Add("Closed LabVIEW $($test.Year) $($test.Bitness)-bit (process $runningId) left running by an earlier job.") + $decision = @(Stop-CiLabVIEW -LabVIEWPath @($test.Path)) | Select-Object -First 1 + if ($decision -and $decision.Stop) { + $notes.Add("Force-closed LabVIEW $($test.Year) $($test.Bitness)-bit (process $($decision.Id)) left running by an earlier job.") + } elseif ($decision) { + $notes.Add("Left LabVIEW $($test.Year) $($test.Bitness)-bit (process $($decision.Id)) running: $($decision.Reason). The tests and the build may load VIs an earlier job left in it.") } # Compiled code of source-only VIs from an earlier job's checkout at the - # same path; LabVIEW rebuilds the cache from this checkout's files. + # same path; LabVIEW rebuilds the cache from this checkout's files. Not + # while that LabVIEW still runs and uses the cache. $cacheRoot = Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'LabVIEW Data\VIObjCache' $cacheDirs = @(Get-ChildItem -LiteralPath $cacheRoot -Directory -Filter "$($test.Year - 2000).0*" -ErrorAction SilentlyContinue) + if ($cacheDirs.Count -gt 0 -and (Get-LabVIEWProcess $test.Path)) { + $notes.Add("Kept the compiled object cache of LabVIEW $($test.Year) ($($cacheDirs[0].FullName)): that LabVIEW is still running.") + $cacheDirs = @() + } foreach ($dir in $cacheDirs) { try { Remove-Item -LiteralPath $dir.FullName -Recurse -Force -ErrorAction Stop @@ -180,18 +211,6 @@ if ($Fix -and $CleanStart -and $test) { } } -$compare = $null -if ($For -in 'Compare', 'All' -and $installs.Count -gt 0) { - $compare = Select-Requested $env:REQUESTED_COMPARE_PATH 'LABVIEW_COMPARE_PATH' $installs - if (-not $compare) { - # Newest first; of the same version the 32-bit one. - $compare = $installs | Sort-Object @{ Expression = 'Year'; Descending = $true }, @{ Expression = { if ($_.Bitness -eq '32') { 0 } else { 1 } } } | Select-Object -First 1 - } - if ($compare -and $cliYear -and $compare.Year -lt $cliYear) { - $notes.Add("The comparison LabVIEW ($($compare.Year)) is older than LabVIEW CLI ($cliYear); its comparison operation will not load there.") - } -} - # --- VI Server ports ----------------------------------------------------------- # The port each installed LabVIEW is meant to have: VIPM's record of it if # VIPM knows it (VIPM puts a LabVIEW back on that port whenever it starts it, diff --git a/tools/setup/README.md b/tools/setup/README.md index 410713f..82fecab 100644 --- a/tools/setup/README.md +++ b/tools/setup/README.md @@ -160,3 +160,15 @@ The three `fake ... broken vi.vi` files are reported as bad on purpose; the `PSSecurityException`. - Only one runner should carry the `self-hosted` label unless all of them are set up as described here. +- At the start of every job, and when a LabVIEW does not listen on its VI + Server port, CI force-closes the test LabVIEW and the comparison LabVIEW it + chose (and, at the start, a VIPM Desktop left over from an earlier job). + Anything open in them is lost. No other LabVIEW on the machine is touched, + and a chosen one that has unsaved changes (a window title with `*`) is left + running, with a warning in the job summary. On a developer machine, work + in a LabVIEW CI does not use (see "LabVIEW for the VI comparison"). +- `CI_DEDICATED_MACHINE=1` in the runner's environment (for example a line + `CI_DEDICATED_MACHINE=1` in the runner's `.env` file, then restart the + runner) says nobody works on the machine: CI then closes the test and + comparison LabVIEWs also when they have unsaved changes. Leave it unset on + a machine someone develops on. From adb49421f8e76ec004027568ec0e37a3dfc64ecf Mon Sep 17 00:00:00 2001 From: Calmy Jane Date: Sun, 25 Oct 2026 21:38:06 +0400 Subject: [PATCH 2/9] Share one native-command wrapper and the vipm and gh lookups Four copies of the same code ran a console program with stderr merged into its output while keeping Windows PowerShell from stopping on the stderr lines (Invoke-CliTest.ps1, two in New-ViDiffReport.ps1, Test-InstalledPackage.ps1), and three scripts had their own list of places to look for vipm or gh. LabVIEWCi.psm1 now has Invoke-NativeCommand (returns ExitCode and Output), Get-VipmPath and Get-GhPath, and the scripts call them. Behaviour is the same, with three small differences: an empty stderr line from the VI comparison is reported as its text, as the other scripts already did; a program that is not installed returns exit code -1 with a "not recognized" line in the output; and Test-InstalledPackage.ps1 and Publish-PrReport.ps1 now also look for vipm and gh under ProgramW6432, like Resolve-CiEnvironment.ps1 did already. Co-Authored-By: Claude Opus 5.5 --- tools/ci/Invoke-CliTest.ps1 | 17 +++++---------- tools/ci/LabVIEWCi.psm1 | 33 +++++++++++++++++++++++++++++- tools/ci/New-ViDiffReport.ps1 | 25 ++++++++-------------- tools/ci/Publish-PrReport.ps1 | 7 ++----- tools/ci/Resolve-CiEnvironment.ps1 | 7 ++----- tools/ci/Test-InstalledPackage.ps1 | 19 ++++++----------- 6 files changed, 55 insertions(+), 53 deletions(-) diff --git a/tools/ci/Invoke-CliTest.ps1 b/tools/ci/Invoke-CliTest.ps1 index 4a7e055..76fe403 100644 --- a/tools/ci/Invoke-CliTest.ps1 +++ b/tools/ci/Invoke-CliTest.ps1 @@ -41,18 +41,11 @@ if (-not (Get-LabVIEWCliPath)) { } function Invoke-RunVI([int]$Port) { - # LabVIEW CLI writes its errors to stderr; Windows PowerShell turns - # redirected stderr lines into errors, so they must not stop the script. - $previous = $ErrorActionPreference - $ErrorActionPreference = 'Continue' - $out = & LabVIEWCLI -OperationName RunVI -VIPath $VIPath -PortNumber $Port ` - -LabVIEWPath $LabVIEWPath 2>&1 | ForEach-Object { - # An empty stderr line arrives as an error record whose text is its type name. - if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.Exception.Message } else { "$_" } - } | Out-String - $script:code = $LASTEXITCODE - $ErrorActionPreference = $previous - return $out + # LabVIEW CLI writes its errors to stderr; Invoke-NativeCommand keeps them + # as text in the output. + $run = Invoke-NativeCommand 'LabVIEWCLI' @('-OperationName', 'RunVI', '-VIPath', $VIPath, '-PortNumber', $Port, '-LabVIEWPath', $LabVIEWPath) + $script:code = $run.ExitCode + return ($run.Output | Out-String) } $output = Invoke-RunVI $PortNumber diff --git a/tools/ci/LabVIEWCi.psm1 b/tools/ci/LabVIEWCi.psm1 index 757f5e0..dce4be1 100644 --- a/tools/ci/LabVIEWCi.psm1 +++ b/tools/ci/LabVIEWCi.psm1 @@ -408,7 +408,38 @@ function Get-LabVIEWCliPath { "$env:ProgramFiles\National Instruments\Shared\LabVIEW CLI\LabVIEWCLI.exe") } +function Get-VipmPath { + <# Path of the VIPM command line (vipm.exe), or $null. #> + Find-Tool 'vipm' @( + "$env:ProgramW6432\JKI\VI Package Manager\support\vipm.exe", + "$env:ProgramFiles\JKI\VI Package Manager\support\vipm.exe", + "${env:ProgramFiles(x86)}\JKI\VI Package Manager\support\vipm.exe") +} + +function Get-GhPath { + <# Path of the GitHub CLI (gh.exe), or $null. #> + Find-Tool 'gh' @("$env:ProgramW6432\GitHub CLI\gh.exe", "$env:ProgramFiles\GitHub CLI\gh.exe") +} + +function Invoke-NativeCommand { + <# Runs a console program with its standard error merged into its output + and returns ExitCode and Output (one string per line). Windows + PowerShell turns redirected stderr lines into error records; here they + become plain text and never stop the caller, and an empty stderr line + arrives as its message, not as the record's type name. A program that + does not exist gives exit code -1 and a "not recognized" line. #> + param([Parameter(Mandatory = $true)][string]$FilePath, [string[]]$ArgumentList = @()) + $ErrorActionPreference = 'Continue' + if (-not (Get-Command $FilePath -CommandType Application -ErrorAction SilentlyContinue)) { + return [pscustomobject]@{ ExitCode = -1; Output = @("$FilePath is not recognized as the name of a program (not installed or not on PATH).") } + } + $output = @(& $FilePath @ArgumentList 2>&1 | ForEach-Object { + if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.Exception.Message } else { "$_" } + }) + return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = $output } +} + Export-ModuleMember -Function Get-LabVIEWInstall, Get-IniValue, Set-IniValue, Get-ListeningPort, Get-PortOwner, Get-FreePort, Get-LabVIEWProcess, Resolve-ViServerPort, Find-Tool, Get-LabVIEWCliPath, Get-ExeBitness, Get-VipmPort, Stop-LeftoverVipm, Test-CiDedicatedMachine, Get-ProcessWindowTitle, Select-LabVIEWToStop, - Get-RunningLabVIEW, Stop-CiLabVIEW + Get-RunningLabVIEW, Stop-CiLabVIEW, Get-VipmPath, Get-GhPath, Invoke-NativeCommand diff --git a/tools/ci/New-ViDiffReport.ps1 b/tools/ci/New-ViDiffReport.ps1 index 6ea90e5..9c2d637 100644 --- a/tools/ci/New-ViDiffReport.ps1 +++ b/tools/ci/New-ViDiffReport.ps1 @@ -55,15 +55,10 @@ if (-not (Test-Path $framePrinter)) { $framePrinter = $null; Write-Warning "$(Jo function Invoke-CliComparison([string]$Vi1, [string]$Vi2, [string]$ReportPath) { # LabVIEW CLI writes its error text to stderr; keep it for the report. - # Windows PowerShell turns redirected stderr lines into errors, so they - # must not stop the script here. - $previous = $ErrorActionPreference - $ErrorActionPreference = 'Continue' - $output = & LabVIEWCLI -OperationName CreateComparisonReport -VI1 $Vi1 -VI2 $Vi2 ` - -ReportType html -ReportPath $ReportPath -o -c -nobdcosm -nofppos ` - -LabVIEWPath $LabVIEWPath -PortNumber $script:PortNumber 2>&1 | ForEach-Object { "$_" } | Out-String - $ErrorActionPreference = $previous - $output = $output.Trim() + $run = Invoke-NativeCommand 'LabVIEWCLI' @('-OperationName', 'CreateComparisonReport', '-VI1', $Vi1, '-VI2', $Vi2, + '-ReportType', 'html', '-ReportPath', $ReportPath, '-o', '-c', '-nobdcosm', '-nofppos', + '-LabVIEWPath', $LabVIEWPath, '-PortNumber', $script:PortNumber) + $output = ($run.Output | Out-String).Trim() return @{ Ok = (Test-Path $ReportPath) Output = $output @@ -107,15 +102,11 @@ function Invoke-FramePrint([string]$ViPath, [string]$Slug) { New-Item -ItemType Directory -Force $dir | Out-Null $html = Join-Path $dir 'diagram.html' $list = Join-Path $dir 'frames.txt' - $previous = $ErrorActionPreference - $ErrorActionPreference = 'Continue' # The VI's arguments come last; RunVI hands them to Command Line Arguments. - $output = & LabVIEWCLI -OperationName RunVI -LabVIEWPath $LabVIEWPath -PortNumber $script:PortNumber ` - -VIPath $framePrinter $ViPath $html $list 2>&1 | ForEach-Object { - if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.Exception.Message } else { "$_" } - } | Out-String - $code = $LASTEXITCODE - $ErrorActionPreference = $previous + $run = Invoke-NativeCommand 'LabVIEWCLI' @('-OperationName', 'RunVI', '-LabVIEWPath', $LabVIEWPath, '-PortNumber', $script:PortNumber, + '-VIPath', $framePrinter, $ViPath, $html, $list) + $output = $run.Output | Out-String + $code = $run.ExitCode if ($code -ne 0 -or -not (Test-Path $html) -or -not (Test-Path $list)) { return @{ Ok = $false; Output = $output.Trim() } } diff --git a/tools/ci/Publish-PrReport.ps1 b/tools/ci/Publish-PrReport.ps1 index 713716a..e4077e4 100644 --- a/tools/ci/Publish-PrReport.ps1 +++ b/tools/ci/Publish-PrReport.ps1 @@ -23,6 +23,7 @@ param( ) $ErrorActionPreference = 'Stop' +Import-Module (Join-Path $PSScriptRoot 'LabVIEWCi.psm1') -Force $marker = '' $maxLength = 60000 # GitHub rejects comments longer than 65536 characters $utf8 = New-Object System.Text.UTF8Encoding $false @@ -96,11 +97,7 @@ $bodyFile = Join-Path ([System.IO.Path]::GetTempPath()) ("pr_comment_" + [guid]: # gh where it is installed; otherwise the REST API directly, with the same # token (GH_TOKEN), so a runner without the GitHub CLI still gets its report. -$useGh = [bool](Get-Command gh -CommandType Application -ErrorAction SilentlyContinue) -if (-not $useGh) { - $ghDefault = Join-Path $env:ProgramFiles 'GitHub CLI\gh.exe' - if (Test-Path $ghDefault) { $env:PATH = "$(Split-Path $ghDefault);$env:PATH"; $useGh = $true } -} +$useGh = [bool](Get-GhPath) if (-not $useGh) { if (-not $env:GH_TOKEN) { throw 'Neither the GitHub CLI (gh) nor GH_TOKEN is available to post the comment.' } Write-Host 'gh not found; posting through the REST API.' diff --git a/tools/ci/Resolve-CiEnvironment.ps1 b/tools/ci/Resolve-CiEnvironment.ps1 index 81f37d4..968278a 100644 --- a/tools/ci/Resolve-CiEnvironment.ps1 +++ b/tools/ci/Resolve-CiEnvironment.ps1 @@ -108,10 +108,7 @@ $cliYear = $null if ($cli -and ((Get-Item -LiteralPath $cli).VersionInfo.FileVersion -match '^(\d+)\.')) { $m = [int]$Matches[1]; $cliYear = if ($m -ge 2000) { $m } elseif ($m -ge 17) { 2000 + $m } else { $null } } -$vipm = Find-Tool 'vipm' @( - "$env:ProgramW6432\JKI\VI Package Manager\support\vipm.exe", - "$env:ProgramFiles\JKI\VI Package Manager\support\vipm.exe", - "${env:ProgramFiles(x86)}\JKI\VI Package Manager\support\vipm.exe") +$vipm = Get-VipmPath if (-not $vipm) { $notes.Add('vipm (VIPM command line) not found; installing packages and building will fail.') } # Git must be on the PATH before the job starts: without it actions/checkout # downloads a zip instead of cloning, and then the VI diff has no history and @@ -131,7 +128,7 @@ if ($env:GITHUB_WORKSPACE -and -not (Test-Path (Join-Path $env:GITHUB_WORKSPACE $problems.Add('The checkout is not a Git repository (actions/checkout fell back to downloading a zip). The VI diff and VIPM Community Edition need a real clone; see the Git message above.') } -$gh = Find-Tool 'gh' @("$env:ProgramW6432\GitHub CLI\gh.exe", "$env:ProgramFiles\GitHub CLI\gh.exe") +$gh = Get-GhPath if (-not $gh) { $notes.Add('gh (GitHub CLI) not found; the report is posted through the REST API instead.') } if ($Fix) { diff --git a/tools/ci/Test-InstalledPackage.ps1 b/tools/ci/Test-InstalledPackage.ps1 index 421f305..8486ea7 100644 --- a/tools/ci/Test-InstalledPackage.ps1 +++ b/tools/ci/Test-InstalledPackage.ps1 @@ -75,19 +75,12 @@ function Write-Failure([string]$Text) { } function Invoke-Native { - # Runs a console tool, returns its exit code and prints and records its - # output. Windows PowerShell turns stderr lines into errors; they must - # not stop the script. + # Runs a console tool (Invoke-NativeCommand), prints and records its + # output and returns its exit code. param([string]$Exe, [string[]]$Arguments) - $previous = $ErrorActionPreference - $ErrorActionPreference = 'Continue' - $out = & $Exe @Arguments 2>&1 | ForEach-Object { - if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.Exception.Message } else { "$_" } - } - $code = $LASTEXITCODE - $ErrorActionPreference = $previous - foreach ($line in $out) { Write-Line " $line" } - return $code + $run = Invoke-NativeCommand $Exe $Arguments + foreach ($line in $run.Output) { Write-Line " $line" } + return $run.ExitCode } function Test-ServerAnswers { @@ -126,7 +119,7 @@ Write-Line "Package: $VipPath" if (-not $ContentsOnly) { $cli = Get-LabVIEWCliPath if (-not $cli) { Write-Host '::error::LabVIEW CLI (LabVIEWCLI.exe) is not installed.'; exit 1 } - $vipm = Find-Tool 'vipm' @("$env:ProgramFiles\JKI\VI Package Manager\support\vipm.exe", "${env:ProgramFiles(x86)}\JKI\VI Package Manager\support\vipm.exe") + $vipm = Get-VipmPath if (-not $vipm) { Write-Host '::error::The vipm CLI is not installed.'; exit 1 } Write-Line "LabVIEW: $($lvInfo.Path) ($($lvInfo.Year) $($lvInfo.Bitness)-bit), VI Server port $PortNumber" } From 6cd4a5b5c086036e6eeaa6a9d7d8de23571c83b6 Mon Sep 17 00:00:00 2001 From: Calmy Jane Date: Sun, 25 Oct 2026 21:40:11 +0400 Subject: [PATCH 3/9] Name file encodings explicitly and take user paths literally LabVIEW.ini and VIPM's Settings.ini were read and written with [Text.Encoding]::Default, which is the ANSI code page only in Windows PowerShell and UTF-8 in PowerShell 7. Get-AnsiEncoding in LabVIEWCi.psm1 now names the system code page (GetEncoding(0), 1252 if that fails), and Get-IniValue reads with it too. The lines written to GITHUB_ENV, GITHUB_PATH and the job summary go through Add-GitHubFileText as UTF-8 without BOM; Add-Content wrote them in the ANSI code page, so a path with non-ASCII characters reached the next steps garbled. Test-InstalledPackage.ps1 writes its initialize request to a temporary file of its own run and deletes it at the end. Paths given by the caller are passed with -LiteralPath in Invoke-CliTest.ps1, Test-InstalledPackage.ps1, Install-Dependencies.ps1 and Resolve-CiEnvironment.ps1, so a "[" in a folder name is not read as a wildcard. Install-Dependencies.ps1 keeps a VIPM_DESKTOP_LIVELINESS_TIMEOUT that the caller has set instead of replacing it with 600 s. Co-Authored-By: Claude Opus 5.5 --- tools/ci/Invoke-CliTest.ps1 | 2 +- tools/ci/LabVIEWCi.psm1 | 34 ++++++++++++++++++++++++---- tools/ci/Resolve-CiEnvironment.ps1 | 6 ++--- tools/ci/Test-InstalledPackage.ps1 | 17 ++++++++++---- tools/setup/Install-Dependencies.ps1 | 15 ++++++------ 5 files changed, 53 insertions(+), 21 deletions(-) diff --git a/tools/ci/Invoke-CliTest.ps1 b/tools/ci/Invoke-CliTest.ps1 index 76fe403..413605e 100644 --- a/tools/ci/Invoke-CliTest.ps1 +++ b/tools/ci/Invoke-CliTest.ps1 @@ -27,7 +27,7 @@ function Write-Log([string]$Text) { if ($LogFile) { [System.IO.File]::WriteAllText($LogFile, $Text, $utf8) } } -if (-not (Test-Path $VIPath)) { +if (-not (Test-Path -LiteralPath $VIPath)) { $message = "$VIPath does not exist on this branch." Write-Host $message Write-Log $message diff --git a/tools/ci/LabVIEWCi.psm1 b/tools/ci/LabVIEWCi.psm1 index dce4be1..267c889 100644 --- a/tools/ci/LabVIEWCi.psm1 +++ b/tools/ci/LabVIEWCi.psm1 @@ -58,10 +58,33 @@ function Get-LabVIEWInstall { } } +function Get-AnsiEncoding { + <# The system ANSI code page, in which LabVIEW writes LabVIEW.ini and VIPM + its Settings.ini. Named explicitly: [Text.Encoding]::Default is that + code page in Windows PowerShell but UTF-8 in PowerShell 7. + GetEncoding(0) is the system code page in both; 1252 if it fails. #> + if (-not $script:AnsiEncoding) { + try { $script:AnsiEncoding = [System.Text.Encoding]::GetEncoding(0) } + catch { $script:AnsiEncoding = [System.Text.Encoding]::GetEncoding(1252) } + } + return $script:AnsiEncoding +} + +function Add-GitHubFileText { + <# Appends a line to one of the files GitHub Actions reads after a step + (GITHUB_ENV, GITHUB_PATH, GITHUB_OUTPUT, GITHUB_STEP_SUMMARY), as UTF-8 + without BOM, which is what the runner reads. Add-Content would write + the ANSI code page in Windows PowerShell. Does nothing when Path is + empty (outside GitHub Actions). #> + param([string]$Path, [AllowEmptyString()][string]$Text) + if (-not $Path) { return } + [System.IO.File]::AppendAllText($Path, $Text + "`n", (New-Object System.Text.UTF8Encoding $false)) +} + function Get-IniValue([string]$Ini, [string]$Key) { if (-not (Test-Path -LiteralPath $Ini)) { return $null } $pattern = '^\s*' + [regex]::Escape($Key) + '\s*=(.*)$' - foreach ($line in [System.IO.File]::ReadAllLines($Ini)) { + foreach ($line in [System.IO.File]::ReadAllLines($Ini, (Get-AnsiEncoding))) { if ($line -match $pattern) { return $Matches[1].Trim().Trim('"') } } return $null @@ -70,7 +93,7 @@ function Get-IniValue([string]$Ini, [string]$Key) { function Set-IniValue([string]$Ini, [string]$Key, [string]$Value) { <# Sets key=value in the [LabVIEW] section of a LabVIEW.ini. Only call it while that LabVIEW is not running: LabVIEW rewrites the file on exit. #> - $encoding = [System.Text.Encoding]::Default + $encoding = Get-AnsiEncoding # Not "$lines = if (...) { list }": PowerShell would unroll the list into a # fixed-size array, and Insert would fail. $lines = New-Object System.Collections.Generic.List[string] @@ -233,7 +256,7 @@ function Get-VipmPort { $inTargets = $false $locations = @{} $ports = @() - foreach ($line in [System.IO.File]::ReadAllLines($Settings, [System.Text.Encoding]::Default)) { + foreach ($line in [System.IO.File]::ReadAllLines($Settings, (Get-AnsiEncoding))) { if ($line -match '^\s*\[(.+)\]\s*$') { $inTargets = ($Matches[1] -eq 'Targets'); continue } if (-not $inTargets) { continue } if ($line -match '^Locations (\d+)="(.*)"$') { $locations[[int]$Matches[1]] = $Matches[2] } @@ -395,7 +418,7 @@ function Find-Tool { if (-not $hit) { continue } $dir = Split-Path $hit.Path $env:PATH = "$dir;$env:PATH" - if ($env:GITHUB_PATH) { Add-Content -LiteralPath $env:GITHUB_PATH -Value $dir } + Add-GitHubFileText $env:GITHUB_PATH $dir return $hit.Path } return $null @@ -442,4 +465,5 @@ function Invoke-NativeCommand { Export-ModuleMember -Function Get-LabVIEWInstall, Get-IniValue, Set-IniValue, Get-ListeningPort, Get-PortOwner, Get-FreePort, Get-LabVIEWProcess, Resolve-ViServerPort, Find-Tool, Get-LabVIEWCliPath, Get-ExeBitness, Get-VipmPort, Stop-LeftoverVipm, Test-CiDedicatedMachine, Get-ProcessWindowTitle, Select-LabVIEWToStop, - Get-RunningLabVIEW, Stop-CiLabVIEW, Get-VipmPath, Get-GhPath, Invoke-NativeCommand + Get-RunningLabVIEW, Stop-CiLabVIEW, Get-VipmPath, Get-GhPath, Invoke-NativeCommand, Get-AnsiEncoding, + Add-GitHubFileText diff --git a/tools/ci/Resolve-CiEnvironment.ps1 b/tools/ci/Resolve-CiEnvironment.ps1 index 968278a..a1ac912 100644 --- a/tools/ci/Resolve-CiEnvironment.ps1 +++ b/tools/ci/Resolve-CiEnvironment.ps1 @@ -124,7 +124,7 @@ if (-not $git) { } elseif (-not $gitOnPath) { $problems.Add("Git is installed ($git) but not on the PATH the runner started with, so actions/checkout downloaded a zip instead of a repository. Add $(Split-Path $git) to the system PATH and restart the runner.") } -if ($env:GITHUB_WORKSPACE -and -not (Test-Path (Join-Path $env:GITHUB_WORKSPACE '.git'))) { +if ($env:GITHUB_WORKSPACE -and -not (Test-Path -LiteralPath (Join-Path $env:GITHUB_WORKSPACE '.git'))) { $problems.Add('The checkout is not a Git repository (actions/checkout fell back to downloading a zip). The VI diff and VIPM Community Edition need a real clone; see the Git message above.') } @@ -259,7 +259,7 @@ if ($compare) { # --- hand over ------------------------------------------------------------------- foreach ($entry in $result.GetEnumerator()) { Set-Item -Path "env:$($entry.Key)" -Value "$($entry.Value)" - if ($env:GITHUB_ENV) { Add-Content -LiteralPath $env:GITHUB_ENV -Value "$($entry.Key)=$($entry.Value)" } + Add-GitHubFileText $env:GITHUB_ENV "$($entry.Key)=$($entry.Value)" } $summary = New-Object System.Text.StringBuilder @@ -282,7 +282,7 @@ if ($notes.Count -gt 0) { $notes | ForEach-Object { [void]$summary.AppendLine("- $_") } } Write-Host $summary.ToString() -if ($env:GITHUB_STEP_SUMMARY) { Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value $summary.ToString() } +Add-GitHubFileText $env:GITHUB_STEP_SUMMARY $summary.ToString() if ($env:GITHUB_ACTIONS) { $notes | ForEach-Object { Write-Host "::warning::$_" } } if ($problems.Count -gt 0) { diff --git a/tools/ci/Test-InstalledPackage.ps1 b/tools/ci/Test-InstalledPackage.ps1 index 8486ea7..a268467 100644 --- a/tools/ci/Test-InstalledPackage.ps1 +++ b/tools/ci/Test-InstalledPackage.ps1 @@ -83,21 +83,26 @@ function Invoke-Native { return $run.ExitCode } +# The initialize request Test-ServerAnswers posts; a file of this run only, +# deleted at the end. +$script:initializeFile = Join-Path ([System.IO.Path]::GetTempPath()) ('installed-package-initialize_' + [guid]::NewGuid().ToString('N') + '.json') + function Test-ServerAnswers { - $body = '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"installed-package-test","version":"1.0"}}}' - $file = Join-Path ([System.IO.Path]::GetTempPath()) 'installed-package-initialize.json' - [System.IO.File]::WriteAllText($file, $body, $utf8) + if (-not (Test-Path -LiteralPath $script:initializeFile)) { + $body = '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"installed-package-test","version":"1.0"}}}' + [System.IO.File]::WriteAllText($script:initializeFile, $body, $utf8) + } $previous = $ErrorActionPreference $ErrorActionPreference = 'Continue' $status = & curl.exe -s -m 5 -o NUL -w '%{http_code}' -X POST -H 'Content-Type: application/json' ` - -H 'Accept: application/json, text/event-stream' --data-binary "@$file" $ServerUrl 2>$null + -H 'Accept: application/json, text/event-stream' --data-binary "@$($script:initializeFile)" $ServerUrl 2>$null $ErrorActionPreference = $previous return "$status" -eq '200' } # ---------------------------------------------------------------- inputs if (-not $VipPath) { - $newest = Get-ChildItem (Join-Path $RepoDir 'builds') -Filter *.vip -File -ErrorAction SilentlyContinue | + $newest = Get-ChildItem -LiteralPath (Join-Path $RepoDir 'builds') -Filter *.vip -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if (-not $newest) { Write-Host "::error::No -VipPath given and no .vip under $RepoDir\builds."; exit 1 } $VipPath = $newest.FullName @@ -263,6 +268,8 @@ finally { Write-Line 'The package stays installed (-KeepInstalled).' } + Remove-Item -LiteralPath $script:initializeFile -Force -ErrorAction SilentlyContinue + Write-Step 'Result' if ($script:failed) { Write-Line 'FAILED: see the FAIL lines above.' } else { Write-Line 'PASSED: the installed package is clean and its Datalogger example serves MCP.' } [System.IO.File]::WriteAllLines($ReportFile, $script:report, $utf8) diff --git a/tools/setup/Install-Dependencies.ps1 b/tools/setup/Install-Dependencies.ps1 index 5f450f6..e3ef21b 100644 --- a/tools/setup/Install-Dependencies.ps1 +++ b/tools/setup/Install-Dependencies.ps1 @@ -28,20 +28,21 @@ param( ) $ErrorActionPreference = 'Stop' -$repo = (Resolve-Path $RepoDir).Path +$repo = (Resolve-Path -LiteralPath $RepoDir).Path $vipc = Join-Path $repo 'src\LabVIEW MCP Server SDK.vipc' -if (-not (Test-Path $vipc)) { throw "No package configuration at $vipc." } +if (-not (Test-Path -LiteralPath $vipc)) { throw "No package configuration at $vipc." } $target = @('--labview-version', $LabVIEWVersion, '--labview-bitness', $Bitness) # VIPM Desktop goes quiet for minutes while LabVIEW starts and compiles. -$env:VIPM_DESKTOP_LIVELINESS_TIMEOUT = '600' +# A value the caller (a workflow step) has set is kept. +if (-not $env:VIPM_DESKTOP_LIVELINESS_TIMEOUT) { $env:VIPM_DESKTOP_LIVELINESS_TIMEOUT = '600' } # VIPM Community Edition only installs from inside a public Git repository # and looks at the current folder for it, so run vipm from the checkout. -if (-not (Test-Path (Join-Path $repo '.git'))) { +if (-not (Test-Path -LiteralPath (Join-Path $repo '.git'))) { Write-Warning "$repo is not a Git repository; VIPM Community Edition will refuse to install (""Not inside a Git repository""). Clone the repository with Git instead of downloading it." } -Push-Location $repo +Push-Location -LiteralPath $repo try { Write-Host "Installing runtime dependencies from $vipc into LabVIEW $LabVIEWVersion $Bitness-bit ..." & vipm install $vipc @target --yes --timeout 1200 @@ -49,8 +50,8 @@ try { $packageList = Join-Path $repo 'tools\setup\test-packages.txt' $packages = @() - if (Test-Path $packageList) { - $packages = @(Get-Content $packageList | + if (Test-Path -LiteralPath $packageList) { + $packages = @(Get-Content -LiteralPath $packageList | ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') }) } else { Write-Host "No $packageList; only the runtime dependencies are installed." From d64e5b508ff3830bb3ee71a1c8052e510cc961dd Mon Sep 17 00:00:00 2001 From: Calmy Jane Date: Sun, 25 Oct 2026 21:42:19 +0400 Subject: [PATCH 4/9] Fail the VI diff on git errors and escape LabVIEW text in the report New-ViDiffReport.ps1 ignored the exit codes of git diff, merge-base and worktree add. A failed diff looked like "no VI changed" and passed; a failed worktree add left every old version missing. The file list was parsed from quoted, tab-separated output, so a path with non-ASCII characters or quotes came back in git's escaped form and was not found. Now every git call goes through Invoke-Git (LabVIEWCi.psm1), which reads git's output as UTF-8 and throws on a non-zero exit code. The file list comes from "git -c core.quotePath=false diff -z" and is split on NUL (ConvertFrom-GitNameStatus). Stale worktrees of a killed earlier run are pruned first, and a failing clean-up only warns. Difference headings and details from LabVIEW's HTML report, frame captions and folder names are now shown as plain text (ConvertTo-MarkdownText): tags are dropped, and | < > & and @ are escaped, so "" stays visible, a "|" no longer splits a table row and "@name" in a label does not mention anyone. LabVIEW CLI output is wrapped in a code fence longer than any run of backticks in it (Format-MarkdownCodeBlock). Paths are passed with -LiteralPath. Co-Authored-By: Claude Opus 5.5 --- tools/ci/LabVIEWCi.psm1 | 62 +++++++++++++++++++++++++++++++++- tools/ci/New-ViDiffReport.ps1 | 63 ++++++++++++++++++----------------- 2 files changed, 94 insertions(+), 31 deletions(-) diff --git a/tools/ci/LabVIEWCi.psm1 b/tools/ci/LabVIEWCi.psm1 index 267c889..6800758 100644 --- a/tools/ci/LabVIEWCi.psm1 +++ b/tools/ci/LabVIEWCi.psm1 @@ -462,8 +462,68 @@ function Invoke-NativeCommand { return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = $output } } +function Invoke-Git { + <# Runs git with Arguments and returns its standard output, one string + per line. Throws when git exits with a non-zero code, so a failed call + never passes as an empty result. The output is read as UTF-8, which is + what git writes (Windows PowerShell would read it in the console code + page); standard error goes to the console unchanged. #> + param([Parameter(Mandatory = $true)][string[]]$Arguments) + $console = $null + try { $console = [Console]::OutputEncoding; [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false } catch { $console = $null } + try { + $output = @(& git @Arguments) + $code = $LASTEXITCODE + } finally { + if ($console) { try { [Console]::OutputEncoding = $console } catch { } } + } + if ($code -ne 0) { throw "git $($Arguments -join ' ') failed with exit code $code." } + return $output +} + +function ConvertFrom-GitNameStatus { + <# Parses the output of "git diff -z --name-status": NUL-separated fields, + per entry the status, then the path, or the old and the new path for + a rename or copy (R100, C075). Returns Status (first letter), OldPath + and NewPath per entry. #> + param([AllowEmptyString()][AllowNull()][string]$Text) + $fields = @("$Text".Split([char]0) | Where-Object { $_ -ne '' }) + $i = 0 + while ($i -lt $fields.Count) { + $status = $fields[$i].Substring(0, 1) + $paths = if ($status -eq 'R' -or $status -eq 'C') { 2 } else { 1 } + if ($i + $paths -ge $fields.Count) { throw "Unexpected git diff output near '$($fields[$i])'." } + $oldPath = $fields[$i + 1] + $newPath = $fields[$i + $paths] + $i += 1 + $paths + [pscustomobject]@{ Status = $status; OldPath = $oldPath; NewPath = $newPath } + } +} + +function ConvertTo-MarkdownText { + <# Text for a Markdown paragraph or table cell that is shown as written: + & < > as HTML entities (no tags or entities of its own), | escaped so it + does not split a table cell, @ followed by a zero-width space so GitHub + does not turn "@name" into a mention, line breaks as spaces. #> + param([AllowEmptyString()][AllowNull()][string]$Text) + if (-not $Text) { return '' } + $t = $Text -replace '\r?\n', ' ' + return $t.Replace('&', '&').Replace('<', '<').Replace('>', '>').Replace('|', '\|').Replace('@', '@​') +} + +function Format-MarkdownCodeBlock { + <# A fenced Markdown code block around Text. The fence is one backtick + longer than the longest run of backticks in Text (at least three), so + no line of Text can close the block early. #> + param([AllowEmptyString()][AllowNull()][string]$Text) + $longest = 0 + foreach ($run in [regex]::Matches("$Text", '`+')) { if ($run.Length -gt $longest) { $longest = $run.Length } } + $fence = '`' * [Math]::Max(3, $longest + 1) + return "$fence`n$Text`n$fence" +} + Export-ModuleMember -Function Get-LabVIEWInstall, Get-IniValue, Set-IniValue, Get-ListeningPort, Get-PortOwner, Get-FreePort, Get-LabVIEWProcess, Resolve-ViServerPort, Find-Tool, Get-LabVIEWCliPath, Get-ExeBitness, Get-VipmPort, Stop-LeftoverVipm, Test-CiDedicatedMachine, Get-ProcessWindowTitle, Select-LabVIEWToStop, Get-RunningLabVIEW, Stop-CiLabVIEW, Get-VipmPath, Get-GhPath, Invoke-NativeCommand, Get-AnsiEncoding, - Add-GitHubFileText + Add-GitHubFileText, Invoke-Git, ConvertFrom-GitNameStatus, ConvertTo-MarkdownText, Format-MarkdownCodeBlock diff --git a/tools/ci/New-ViDiffReport.ps1 b/tools/ci/New-ViDiffReport.ps1 index 9c2d637..e4bd89f 100644 --- a/tools/ci/New-ViDiffReport.ps1 +++ b/tools/ci/New-ViDiffReport.ps1 @@ -51,7 +51,7 @@ $script:portRetried = $false # Prints every case frame of the new version of each VI. Absent on a base # branch that predates it; the report then shows visible frames only. $framePrinter = Join-Path $PSScriptRoot 'Print Diagram Frames.vi' -if (-not (Test-Path $framePrinter)) { $framePrinter = $null; Write-Warning "$(Join-Path $PSScriptRoot 'Print Diagram Frames.vi') not found; case frames are not printed." } +if (-not (Test-Path -LiteralPath $framePrinter)) { $framePrinter = $null; Write-Warning "$(Join-Path $PSScriptRoot 'Print Diagram Frames.vi') not found; case frames are not printed." } function Invoke-CliComparison([string]$Vi1, [string]$Vi2, [string]$ReportPath) { # LabVIEW CLI writes its error text to stderr; keep it for the report. @@ -60,7 +60,7 @@ function Invoke-CliComparison([string]$Vi1, [string]$Vi2, [string]$ReportPath) { '-LabVIEWPath', $LabVIEWPath, '-PortNumber', $script:PortNumber) $output = ($run.Output | Out-String).Trim() return @{ - Ok = (Test-Path $ReportPath) + Ok = (Test-Path -LiteralPath $ReportPath) Output = $output # -350000: the CLI could not connect to LabVIEW (or the CLI is # missing). Every further comparison would wait for the same timeout. @@ -86,10 +86,10 @@ function Invoke-Comparison([string]$Vi1, [string]$Vi2, [string]$ReportPath) { function Copy-ReportImage([string]$ReportPath, [string]$Source, [string]$Slug) { # $Source is the path as written in the HTML, relative to the report file. $from = Join-Path (Split-Path $ReportPath) $Source - if (-not (Test-Path $from)) { return $null } + if (-not (Test-Path -LiteralPath $from)) { return $null } $targetDir = Join-Path (Join-Path $OutDir 'images') $Slug New-Item -ItemType Directory -Force $targetDir | Out-Null - Copy-Item $from (Join-Path $targetDir (Split-Path $from -Leaf)) -Force + Copy-Item -LiteralPath $from -Destination (Join-Path $targetDir (Split-Path $from -Leaf)) -Force return "images/$Slug/$(Split-Path $from -Leaf)" } @@ -107,7 +107,7 @@ function Invoke-FramePrint([string]$ViPath, [string]$Slug) { '-VIPath', $framePrinter, $ViPath, $html, $list) $output = $run.Output | Out-String $code = $run.ExitCode - if ($code -ne 0 -or -not (Test-Path $html) -or -not (Test-Path $list)) { + if ($code -ne 0 -or -not (Test-Path -LiteralPath $html) -or -not (Test-Path -LiteralPath $list)) { return @{ Ok = $false; Output = $output.Trim() } } # The pictures in the order of the HTML's block diagram section: the whole @@ -144,7 +144,7 @@ function Add-FrameSection([string]$ViPath, [string]$Slug) { $result = Invoke-FramePrint $ViPath $Slug if (-not $result.Ok) { Write-Warning "The case frames of $ViPath could not be printed." - [void]$md.AppendLine("The case frames could not be printed:`n`n``````n$($result.Output)`n```````n") + [void]$md.AppendLine("The case frames could not be printed:`n`n$(Format-MarkdownCodeBlock $result.Output)`n") return $false } $hidden = @($result.Frames | Where-Object { -not $_.Visible }) @@ -160,9 +160,9 @@ function Add-FrameSection([string]$ViPath, [string]$Slug) { [void]$md.AppendLine('| Frame | Picture |') [void]$md.AppendLine('|---|---|') for ($i = 0; $i -lt $result.Images.Count; $i++) { - if (-not (Test-Path $result.Images[$i])) { continue } + if (-not (Test-Path -LiteralPath $result.Images[$i])) { continue } $file = '{0:d2}.png' -f $i - Copy-Item $result.Images[$i] (Join-Path $targetDir $file) -Force + Copy-Item -LiteralPath $result.Images[$i] -Destination (Join-Path $targetDir $file) -Force if ($i -eq 0) { $visible = @($result.Frames | Where-Object { $_.Visible } | ForEach-Object { Format-FrameName $_ }) $caption = if ($visible.Count -gt 0) { "Whole diagram, visible frames: $($visible -join '; ')" } else { 'Whole diagram' } @@ -171,7 +171,8 @@ function Add-FrameSection([string]$ViPath, [string]$Slug) { } else { $caption = "Frame picture $i" } - $caption = $caption -replace '\|', '\|' + # Frame names are selector values such as "" or "a|b". + $caption = ConvertTo-MarkdownText $caption [void]$md.AppendLine("| $caption | ![$file](images/$Slug/frames/$file) |") } [void]$md.AppendLine() @@ -192,15 +193,15 @@ $baseDir = Join-Path $workDir 'base' $htmlDir = Join-Path $workDir 'html' New-Item -ItemType Directory -Force $htmlDir | Out-Null -$changes = @() -foreach ($line in (& git -C $HeadDir diff --name-status --find-renames "$BaseRef...HEAD")) { - $parts = $line -split "`t" - $status = $parts[0].Substring(0, 1) - $oldPath = $parts[1] - $newPath = if ($parts.Count -gt 2) { $parts[2] } else { $parts[1] } - if ($extensions -notcontains [System.IO.Path]::GetExtension($newPath).ToLower()) { continue } - $changes += [pscustomobject]@{ Status = $status; OldPath = $oldPath; NewPath = $newPath } -} +# A worktree of an earlier run that was killed before its clean-up would +# make "worktree add" below fail; forget those whose folder is gone. +Invoke-Git @('-C', $HeadDir, 'worktree', 'prune') | Out-Null + +# -z and core.quotePath=false: NUL-separated and unquoted, so paths with +# spaces, quotes or non-ASCII characters arrive as they are. +$diffOutput = (Invoke-Git @('-C', $HeadDir, '-c', 'core.quotePath=false', 'diff', '-z', '--name-status', '--find-renames', "$BaseRef...HEAD")) -join "`n" +$changes = @(ConvertFrom-GitNameStatus $diffOutput | + Where-Object { $extensions -contains [System.IO.Path]::GetExtension($_.NewPath).ToLower() }) $md = New-Object System.Text.StringBuilder [void]$md.AppendLine('## VI diff report') @@ -227,8 +228,8 @@ $deleted = @($changes | Where-Object { $_.Status -eq 'D' }) [void]$md.AppendLine("$($modified.Count) modified, $($added.Count) added, $($deleted.Count) deleted. Generated by LabVIEW's VI comparison; position and size changes are not shown.") [void]$md.AppendLine() -$mergeBase = (& git -C $HeadDir merge-base $BaseRef HEAD).Trim() -& git -C $HeadDir worktree add --detach $baseDir $mergeBase | Out-Null +$mergeBase = (@(Invoke-Git @('-C', $HeadDir, 'merge-base', $BaseRef, 'HEAD')) -join '').Trim() +Invoke-Git @('-C', $HeadDir, 'worktree', 'add', '--detach', $baseDir, $mergeBase) | Out-Null try { $index = 0 @@ -259,9 +260,7 @@ try { if (-not $result.Ok) { [void]$md.AppendLine('The comparison could not be created:') [void]$md.AppendLine() - [void]$md.AppendLine('```') - [void]$md.AppendLine($result.Output) - [void]$md.AppendLine('```') + [void]$md.AppendLine((Format-MarkdownCodeBlock $result.Output)) [void]$md.AppendLine() $summary += [pscustomobject]@{ Path = $change.NewPath; Status = $change.Status; Count = -1; Image = $null } if ($result.Unreachable) { @@ -298,15 +297,18 @@ try { foreach ($section in $sections) { $body = $section.Groups[1].Value $heading = [regex]::Match($body, '(?s)(.*?)').Groups[1].Value - $heading = [System.Net.WebUtility]::HtmlDecode($heading).Trim() - [void]$md.AppendLine("**$heading**") + # LabVIEW's text, possibly with tags and entities: shown as plain + # text, so a "<", "|" or "@" in a VI or control name stays as it is. + $heading = [System.Net.WebUtility]::HtmlDecode(($heading -replace '<[^>]*>', '')).Trim() + [void]$md.AppendLine("**$(ConvertTo-MarkdownText $heading)**") [void]$md.AppendLine() # LabVIEW marks each change in the images as
. $number = [regex]::Match($heading, '^\d+').Value $letter = 0 foreach ($detail in [regex]::Matches($body, '(?s)
  • (.*?)
  • ')) { $mark = if ($letter -lt 26) { [string][char](65 + $letter) } else { [string]($letter + 1) } - [void]$md.AppendLine("- **$number$mark** " + [System.Net.WebUtility]::HtmlDecode($detail.Groups[1].Value).Trim()) + $text = [System.Net.WebUtility]::HtmlDecode(($detail.Groups[1].Value -replace '<[^>]*>', '')).Trim() + [void]$md.AppendLine("- **$number$mark** " + (ConvertTo-MarkdownText $text)) $letter++ } [void]$md.AppendLine() @@ -341,8 +343,9 @@ try { } } finally { - & git -C $HeadDir worktree remove --force $baseDir | Out-Null - Remove-Item -Recurse -Force $workDir -ErrorAction SilentlyContinue + try { Invoke-Git @('-C', $HeadDir, 'worktree', 'remove', '--force', $baseDir) | Out-Null } + catch { Write-Warning "Could not remove the worktree $baseDir ($($_.Exception.Message)); 'git worktree prune' cleans it up." } + Remove-Item -LiteralPath $workDir -Recurse -Force -ErrorAction SilentlyContinue } [System.IO.File]::WriteAllText((Join-Path $OutDir 'report.md'), $md.ToString(), $utf8) @@ -370,7 +373,7 @@ function Add-ChangedTable($Rows) { $name = [System.IO.Path]::GetFileName($row.Path) $folder = [System.IO.Path]::GetDirectoryName($row.Path) -replace '\\', '/' $count = if ($row.Count -eq -2) { 'not compared' } elseif ($row.Count -lt 0) { 'comparison failed' } elseif ($row.Count -eq 0) { 'cosmetic only' } else { "$($row.Count)" } - [void]$sm.AppendLine("| ``$name``
    $folder | $count | $(Format-Thumb $row.Image 220) |") + [void]$sm.AppendLine("| ``$name``
    $(ConvertTo-MarkdownText $folder) | $count | $(Format-Thumb $row.Image 220) |") } [void]$sm.AppendLine() } @@ -393,7 +396,7 @@ if ($addedRows.Count -gt 0) { foreach ($row in $addedRows) { $name = [System.IO.Path]::GetFileName($row.Path) $folder = [System.IO.Path]::GetDirectoryName($row.Path) -replace '\\', '/' - [void]$sm.AppendLine("| ``$name``
    $folder | $(Format-Thumb $row.Image 200) |") + [void]$sm.AppendLine("| ``$name``
    $(ConvertTo-MarkdownText $folder) | $(Format-Thumb $row.Image 200) |") } [void]$sm.AppendLine() [void]$sm.AppendLine('') From 523bd37b77e6f90580bd42568c4c865484d97ba9 Mon Sep 17 00:00:00 2001 From: Calmy Jane Date: Sun, 25 Oct 2026 21:46:17 +0400 Subject: [PATCH 5/9] Check every git and gh call when publishing the review report Publish-PrReport.ps1 checked only the exit code of the push. A failed worktree add, commit or rev-parse went unnoticed; it built the report commit on a fixed temporary branch, assets-tmp, which a cancelled earlier run could leave behind and which was force-deleted afterwards; a failed comment lookup through gh was taken as "no comment yet" and posted a second report; only the first 100 comments were searched; and any comment with the marker was overwritten, whoever had written it. Now every git call goes through Invoke-Git and fails the step on an error. The report commit is built without any branch: a worktree with --no-checkout (empty index), write-tree and commit-tree, pushed by its id to pr-assets/pr-. The comment lookup checks gh's exit code, reads all pages (gh api --paginate, or page by page through the REST API) and edits only a comment that carries the marker and was written by the user the token belongs to (github-actions[bot] in the workflow, whose token cannot read /user). Otherwise a new comment is posted. For checkouts without persisted credentials the push uses GH_TOKEN, sent as the same Authorization header actions/checkout would store, through GIT_CONFIG_COUNT/KEY/VALUE of that one git call: it is not on a command line and not written to a config file. A checkout that still has its own header, or a local run without GH_TOKEN, pushes as before. Invoke-Utf8Command (LabVIEWCi.psm1) runs git and gh with their output read as UTF-8. Co-Authored-By: Claude Opus 5.5 --- tools/ci/LabVIEWCi.psm1 | 30 ++++--- tools/ci/Publish-PrReport.ps1 | 146 ++++++++++++++++++++++++---------- 2 files changed, 122 insertions(+), 54 deletions(-) diff --git a/tools/ci/LabVIEWCi.psm1 b/tools/ci/LabVIEWCi.psm1 index 6800758..4f46e5f 100644 --- a/tools/ci/LabVIEWCi.psm1 +++ b/tools/ci/LabVIEWCi.psm1 @@ -462,23 +462,31 @@ function Invoke-NativeCommand { return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = $output } } -function Invoke-Git { - <# Runs git with Arguments and returns its standard output, one string - per line. Throws when git exits with a non-zero code, so a failed call - never passes as an empty result. The output is read as UTF-8, which is - what git writes (Windows PowerShell would read it in the console code - page); standard error goes to the console unchanged. #> - param([Parameter(Mandatory = $true)][string[]]$Arguments) +function Invoke-Utf8Command { + <# Runs a console program that writes UTF-8 (git, gh) and returns + ExitCode and Output (its standard output, one string per line, read as + UTF-8; Windows PowerShell would read it in the console code page). + Standard error goes to the console unchanged. #> + param([Parameter(Mandatory = $true)][string]$FilePath, [string[]]$ArgumentList = @()) $console = $null try { $console = [Console]::OutputEncoding; [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false } catch { $console = $null } try { - $output = @(& git @Arguments) + $output = @(& $FilePath @ArgumentList) $code = $LASTEXITCODE } finally { if ($console) { try { [Console]::OutputEncoding = $console } catch { } } } - if ($code -ne 0) { throw "git $($Arguments -join ' ') failed with exit code $code." } - return $output + return [pscustomobject]@{ ExitCode = $code; Output = $output } +} + +function Invoke-Git { + <# Runs git with Arguments (Invoke-Utf8Command) and returns its standard + output, one string per line. Throws when git exits with a non-zero + code, so a failed call never passes as an empty result. #> + param([Parameter(Mandatory = $true)][string[]]$Arguments) + $run = Invoke-Utf8Command 'git' $Arguments + if ($run.ExitCode -ne 0) { throw "git $($Arguments -join ' ') failed with exit code $($run.ExitCode)." } + return $run.Output } function ConvertFrom-GitNameStatus { @@ -526,4 +534,4 @@ Export-ModuleMember -Function Get-LabVIEWInstall, Get-IniValue, Set-IniValue, Ge Get-PortOwner, Get-FreePort, Get-LabVIEWProcess, Resolve-ViServerPort, Find-Tool, Get-LabVIEWCliPath, Get-ExeBitness, Get-VipmPort, Stop-LeftoverVipm, Test-CiDedicatedMachine, Get-ProcessWindowTitle, Select-LabVIEWToStop, Get-RunningLabVIEW, Stop-CiLabVIEW, Get-VipmPath, Get-GhPath, Invoke-NativeCommand, Get-AnsiEncoding, - Add-GitHubFileText, Invoke-Git, ConvertFrom-GitNameStatus, ConvertTo-MarkdownText, Format-MarkdownCodeBlock + Add-GitHubFileText, Invoke-Utf8Command, Invoke-Git, ConvertFrom-GitNameStatus, ConvertTo-MarkdownText, Format-MarkdownCodeBlock diff --git a/tools/ci/Publish-PrReport.ps1 b/tools/ci/Publish-PrReport.ps1 index e4077e4..c7b25be 100644 --- a/tools/ci/Publish-PrReport.ps1 +++ b/tools/ci/Publish-PrReport.ps1 @@ -7,10 +7,18 @@ Pull request comments cannot carry uploaded images through the API, so the diff images are pushed to a branch of their own (pr-assets/pr-, one commit, replaced on every run) and the comment links to them by commit. -The comment is updated in place on later runs; it is found by a hidden marker. +The comment is updated in place on later runs: the comment that carries a +hidden marker and was written by the same GitHub user (github-actions[bot] +in the workflow) is edited, looking through all comments of the pull +request. A marked comment of another user is left alone and a new one is +posted. -Needs git push access to the repository (the checkout's own credentials) and -GH_TOKEN for the gh CLI. Delete the pr-assets branch once the pull request is +Needs GH_TOKEN for gh or the REST API, and push access to the repository. +When GH_TOKEN is set and the checkout has no credentials of its own (the +workflow checks out with persist-credentials: false), the push sends +GH_TOKEN as an HTTP header for that one git call, through the environment, +not the command line. Without GH_TOKEN (a local run) git pushes with the +user's own credentials. Delete the pr-assets branch once the pull request is closed. #> param( @@ -30,42 +38,68 @@ $utf8 = New-Object System.Text.UTF8Encoding $false $body = New-Object System.Text.StringBuilder [void]$body.AppendLine($marker) -if ($TestReport -and (Test-Path $TestReport)) { +if ($TestReport -and (Test-Path -LiteralPath $TestReport)) { [void]$body.AppendLine([System.IO.File]::ReadAllText($TestReport)) } +function Push-Report([string]$WorkTree, [string]$RefSpec) { + # A checkout made with persist-credentials: false has no credentials for + # the push; GH_TOKEN is then sent as the header actions/checkout would + # have stored, through GIT_CONFIG_* variables of this one call, so it + # appears neither on a command line nor in a config file. A checkout + # that still has such a header, or a local run without GH_TOKEN, pushes + # with what git already has. + $own = Invoke-NativeCommand 'git' @('-C', $WorkTree, 'config', '--get-regexp', '^http\..*\.extraheader$') + $useToken = $env:GH_TOKEN -and ($own.ExitCode -ne 0 -or $own.Output.Count -eq 0) + $names = 'GIT_CONFIG_COUNT', 'GIT_CONFIG_KEY_0', 'GIT_CONFIG_VALUE_0' + $saved = @{} + foreach ($n in $names) { $saved[$n] = [Environment]::GetEnvironmentVariable($n, 'Process') } + try { + if ($useToken) { + $server = if ($env:GITHUB_SERVER_URL) { $env:GITHUB_SERVER_URL.TrimEnd('/') } else { 'https://github.com' } + $basic = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("x-access-token:$env:GH_TOKEN")) + $env:GIT_CONFIG_COUNT = '1' + $env:GIT_CONFIG_KEY_0 = "http.$server/.extraheader" + $env:GIT_CONFIG_VALUE_0 = "AUTHORIZATION: basic $basic" + } + Invoke-Git @('-C', $WorkTree, 'push', '--force', '--quiet', 'origin', $RefSpec) | Out-Null + } + finally { + foreach ($n in $names) { [Environment]::SetEnvironmentVariable($n, $saved[$n], 'Process') } + } +} + $diffReport = if ($DiffDir) { Join-Path $DiffDir 'report.md' } else { $null } -if ($diffReport -and (Test-Path $diffReport)) { +if ($diffReport -and (Test-Path -LiteralPath $diffReport)) { $diff = [System.IO.File]::ReadAllText($diffReport) $summaryFile = Join-Path $DiffDir 'summary.md' - $summary = if (Test-Path $summaryFile) { [System.IO.File]::ReadAllText($summaryFile) } else { $null } + $summary = if (Test-Path -LiteralPath $summaryFile) { [System.IO.File]::ReadAllText($summaryFile) } else { $null } $imageDir = Join-Path $DiffDir 'images' $sha = $null - if (Test-Path $imageDir) { - # Commit the full report and its images on an orphan branch through a - # temporary worktree, so the main checkout and its credentials are - # reused untouched. GitHub renders report.md there with its images, - # which is the "full diff" page the comment links to. + if (Test-Path -LiteralPath $imageDir) { + # Commit the full report and its images as a commit without parent, + # built in a temporary worktree without checkout (its index starts + # empty) and pushed by its id, so no branch is created locally and + # the main checkout is left untouched. GitHub renders report.md there + # with its images, which is the "full diff" page the comment links to. $branch = "pr-assets/pr-$PrNumber" - $tree = Join-Path ([System.IO.Path]::GetTempPath()) ("assets_" + [guid]::NewGuid().ToString('N').Substring(0, 8)) - & git -C $RepoDir worktree add --detach $tree HEAD | Out-Null + $tree = Join-Path ([System.IO.Path]::GetTempPath()) ("assets_" + [guid]::NewGuid().ToString('N')) + Invoke-Git @('-C', $RepoDir, 'worktree', 'prune') | Out-Null + Invoke-Git @('-C', $RepoDir, 'worktree', 'add', '--detach', '--no-checkout', $tree, 'HEAD') | Out-Null try { - & git -C $tree checkout --quiet --orphan assets-tmp - & git -C $tree rm -rf --quiet . | Out-Null - Copy-Item $imageDir (Join-Path $tree 'images') -Recurse + Copy-Item -LiteralPath $imageDir -Destination (Join-Path $tree 'images') -Recurse [System.IO.File]::WriteAllText((Join-Path $tree 'report.md'), $diff, $utf8) [System.IO.File]::WriteAllText((Join-Path $tree 'README.md'), "Review report of pull request #$PrNumber, see report.md. Safe to delete after the pull request is closed.`n", $utf8) - & git -C $tree add -A | Out-Null - & git -C $tree -c user.name='github-actions[bot]' -c user.email='41898282+github-actions[bot]@users.noreply.github.com' ` - commit --quiet -m "Review report for pull request $PrNumber" | Out-Null - $sha = (& git -C $tree rev-parse HEAD).Trim() - & git -C $tree push --force --quiet origin "HEAD:refs/heads/$branch" - if ($LASTEXITCODE -ne 0) { throw "Pushing the report to $branch failed." } + Invoke-Git @('-C', $tree, 'add', '--', 'images', 'report.md', 'README.md') | Out-Null + $treeId = (@(Invoke-Git @('-C', $tree, 'write-tree')) -join '').Trim() + $sha = (@(Invoke-Git @('-C', $tree, '-c', 'user.name=github-actions[bot]', '-c', 'user.email=41898282+github-actions[bot]@users.noreply.github.com', + 'commit-tree', $treeId, '-m', "Review report for pull request $PrNumber")) -join '').Trim() + Push-Report $tree "${sha}:refs/heads/$branch" } finally { - & git -C $RepoDir worktree remove --force $tree | Out-Null - & git -C $RepoDir branch --quiet -D assets-tmp + try { Invoke-Git @('-C', $RepoDir, 'worktree', 'remove', '--force', $tree) | Out-Null } + catch { Write-Warning "Could not remove the worktree $tree ($($_.Exception.Message)); 'git worktree prune' cleans it up." } } } @@ -103,37 +137,63 @@ if (-not $useGh) { Write-Host 'gh not found; posting through the REST API.' } $apiHeaders = @{ Authorization = "Bearer $env:GH_TOKEN"; Accept = 'application/vnd.github+json'; 'X-GitHub-Api-Version' = '2022-11-28' } +$apiRoot = if ($env:GITHUB_API_URL) { $env:GITHUB_API_URL.TrimEnd('/') } else { 'https://api.github.com' } -function Invoke-GitHubApi([string]$Method, [string]$Path, [string]$BodyFile) { +function Send-Comment([string]$Method, [string]$Path, [string]$BodyFile) { + # POST or PATCH of a comment body; throws when GitHub refuses it. if ($useGh) { - if ($BodyFile) { - & gh api --method $Method $Path -F "body=@$BodyFile" --silent - } else { - return (& gh api --method $Method $Path | Out-String) | ConvertFrom-Json - } - if ($LASTEXITCODE -ne 0) { throw "GitHub API $Method $Path failed." } + $run = Invoke-Utf8Command 'gh' @('api', '--method', $Method, $Path, '-F', "body=@$BodyFile", '--silent') + if ($run.ExitCode -ne 0) { throw "GitHub API $Method $Path failed (gh exit code $($run.ExitCode))." } return } - $parameters = @{ Method = $Method; Uri = "https://api.github.com/$Path"; Headers = $apiHeaders; UseBasicParsing = $true } - if ($BodyFile) { - $json = @{ body = [System.IO.File]::ReadAllText($BodyFile) } | ConvertTo-Json -Compress - $parameters['Body'] = [System.Text.Encoding]::UTF8.GetBytes($json) - $parameters['ContentType'] = 'application/json; charset=utf-8' + $json = @{ body = [System.IO.File]::ReadAllText($BodyFile) } | ConvertTo-Json -Compress + Invoke-RestMethod -Method $Method -Uri "$apiRoot/$Path" -Headers $apiHeaders -UseBasicParsing ` + -Body ([System.Text.Encoding]::UTF8.GetBytes($json)) -ContentType 'application/json; charset=utf-8' | Out-Null +} + +function Get-PrComment { + # Every comment of the pull request, all pages, as id, login and body. + if ($useGh) { + # --jq prints one compact JSON object per line, also across pages. + $run = Invoke-Utf8Command 'gh' @('api', '--paginate', "repos/$Repo/issues/$PrNumber/comments?per_page=100", '--jq', '.[] | {id: .id, login: .user.login, body: .body}') + if ($run.ExitCode -ne 0) { throw "Reading the comments of pull request #$PrNumber failed (gh exit code $($run.ExitCode))." } + return @($run.Output | Where-Object { $_ } | ForEach-Object { $_ | ConvertFrom-Json }) + } + $all = @() + for ($page = 1; ; $page++) { + $result = Invoke-RestMethod -Method Get -Uri "$apiRoot/repos/$Repo/issues/$PrNumber/comments?per_page=100&page=$page" -Headers $apiHeaders -UseBasicParsing + $items = @($result) + $all += @($items | ForEach-Object { [pscustomobject]@{ id = $_.id; login = $_.user.login; body = $_.body } }) + if ($items.Count -lt 100) { break } + } + return $all +} + +function Get-CommentAuthor { + # The login comments are posted as. The workflow's GITHUB_TOKEN may not + # read /user; it always posts as github-actions[bot]. + $login = $null + if ($useGh) { + $run = Invoke-NativeCommand 'gh' @('api', 'user', '--jq', '.login') + if ($run.ExitCode -eq 0) { $login = ($run.Output -join '').Trim() } + } else { + try { $login = (Invoke-RestMethod -Method Get -Uri "$apiRoot/user" -Headers $apiHeaders -UseBasicParsing).login } catch { $login = $null } } - return Invoke-RestMethod @parameters + if ($login) { return $login } + if ($env:GITHUB_ACTIONS -eq 'true') { return 'github-actions[bot]' } + throw 'Could not find out which GitHub user posts the report (GET /user failed).' } try { - # Looks at the first 100 comments; the report comment is posted early. - $comments = Invoke-GitHubApi GET "repos/$Repo/issues/$PrNumber/comments?per_page=100" - $existing = @($comments | Where-Object { $_.body -like "*$marker*" } | ForEach-Object { $_.id }) | Select-Object -First 1 + $author = Get-CommentAuthor + $existing = @(Get-PrComment | Where-Object { "$($_.body)".Contains($marker) -and $_.login -eq $author } | ForEach-Object { $_.id }) | Select-Object -First 1 if ($existing) { - Invoke-GitHubApi PATCH "repos/$Repo/issues/comments/$existing" $bodyFile | Out-Null + Send-Comment PATCH "repos/$Repo/issues/comments/$existing" $bodyFile } else { - Invoke-GitHubApi POST "repos/$Repo/issues/$PrNumber/comments" $bodyFile | Out-Null + Send-Comment POST "repos/$Repo/issues/$PrNumber/comments" $bodyFile } } finally { - Remove-Item $bodyFile -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $bodyFile -ErrorAction SilentlyContinue } Write-Host "Report published on pull request #$PrNumber." From e45719deec7a2a0032fdd8cf7970b09da09d8271 Mon Sep 17 00:00:00 2001 From: Calmy Jane Date: Sun, 25 Oct 2026 21:49:02 +0400 Subject: [PATCH 6/9] Read the Caraya report by its structure and escape its table cells Convert-CarayaReport.ps1 took the deepest indented lines as the asserts. A single line one level deeper than the rest moved the assert level down, and every test disappeared from the table. It also cut every assert label at its last " - ", so a label such as "fake_tool_arrays - intarray has items of type integer" was shown as "fake_tool_arrays". Labels went into the table as they were, so a "|" split the row, "" vanished as an HTML tag and "@name" mentioned someone, and the protocol tester's output could close its own code fence. The report is now read by its structure, described in the script: caller lines each at their own depth, then the tests at one depth, each followed by its asserts one level deeper. The assert level is the depth most lines share, the tests are one level above it, and anything deeper belongs to the current test. Only test lines are split into label and VI. Cells go through ConvertTo-MarkdownText, the protocol output through Format-MarkdownCodeBlock, and both reports are read as UTF-8 with -LiteralPath. TestStatus and ProtocolStatus accept "not-run", which the pull request workflow passes when it skipped the step because finding LabVIEW or installing the packages failed; the report then says so instead of "no per-test report was produced". On a real report from the runner machine (64 tests) the table is the same apart from the full assert labels. Co-Authored-By: Claude Opus 5.5 --- tools/ci/Convert-CarayaReport.ps1 | 90 +++++++++++++++++++++---------- 1 file changed, 61 insertions(+), 29 deletions(-) diff --git a/tools/ci/Convert-CarayaReport.ps1 b/tools/ci/Convert-CarayaReport.ps1 index 5ad160e..d96da04 100644 --- a/tools/ci/Convert-CarayaReport.ps1 +++ b/tools/ci/Convert-CarayaReport.ps1 @@ -9,9 +9,14 @@ Markdown table with one row per test and its asserts. TestStatus is the exit code of tools\ci\Invoke-CliTest.ps1 for the suite; with 2 (LabVIEW not reachable) the report says that the tests did not run -instead of showing a failure. ProtocolReportPath and ProtocolStatus add a -section for tests\Run_Protocol_Tests_CLI.vi (tools\test\Test-McpServer.ps1 -against a running server). +instead of showing a failure, and with "not-run" (the workflow skipped the +step because finding LabVIEW or installing the packages failed) it says +that. ProtocolReportPath and ProtocolStatus (the same values) add a section +for tests\Run_Protocol_Tests_CLI.vi (tools\test\Test-McpServer.ps1 against a +running server). + +Labels and VI names are escaped for the Markdown table, and the protocol +tester's output is put in a code fence that no line of it can close. Exit code is always 0; whether the run passed is decided by the test step. #> @@ -24,6 +29,7 @@ param( ) $ErrorActionPreference = 'Stop' +Import-Module (Join-Path $PSScriptRoot 'LabVIEWCi.psm1') -Force $utf8 = New-Object System.Text.UTF8Encoding $false $md = New-Object System.Text.StringBuilder @@ -36,18 +42,17 @@ function Add-ProtocolSection { '0' { [void]$md.AppendLine(':white_check_mark: `Test-McpServer.ps1` passed against the test server.') } '2' { [void]$md.AppendLine(':warning: Not run: LabVIEW could not be reached (LabVIEW CLI error -350000).') } '3' { [void]$md.AppendLine('Not run: `tests\Run_Protocol_Tests_CLI.vi` does not exist on this branch.') } + 'not-run' { [void]$md.AppendLine(':warning: Not run: an earlier step (finding LabVIEW, installing the packages) failed, or LabVIEW was not reachable; see the job log.') } default { [void]$md.AppendLine(':x: `Test-McpServer.ps1` reported failed required checks against the test server.') } } [void]$md.AppendLine() - if ($ProtocolReportPath -and (Test-Path $ProtocolReportPath)) { - $lines = @(Get-Content $ProtocolReportPath) + if ($ProtocolStatus -ne 'not-run' -and $ProtocolReportPath -and (Test-Path -LiteralPath $ProtocolReportPath)) { + $lines = @(Get-Content -LiteralPath $ProtocolReportPath -Encoding UTF8) $fails = @($lines | Where-Object { $_ -match '^\[FAIL\] \(required\)' }) $open = if ($ProtocolStatus -ne '0') { ' open' } else { '' } [void]$md.AppendLine("Protocol tester output ($($fails.Count) failed required checks)") [void]$md.AppendLine() - [void]$md.AppendLine('```') - foreach ($line in $lines) { [void]$md.AppendLine($line) } - [void]$md.AppendLine('```') + [void]$md.AppendLine((Format-MarkdownCodeBlock ($lines -join "`n"))) [void]$md.AppendLine() [void]$md.AppendLine('') [void]$md.AppendLine() @@ -69,7 +74,14 @@ if ($TestStatus -eq '2') { return } -if (-not (Test-Path $ReportPath)) { +if ($TestStatus -eq 'not-run') { + [void]$md.AppendLine(':warning: The tests did not run: finding LabVIEW or installing the packages failed before them. See the job log.') + [void]$md.AppendLine() + Save-Report + return +} + +if (-not (Test-Path -LiteralPath $ReportPath)) { [void]$md.AppendLine('No per-test report was produced. `tests\Run_Tests_CLI.vi` on this branch does not write `tests\results\caraya-report.txt` yet (update the branch from main), or the run stopped before the suite finished.') Save-Report return @@ -80,35 +92,53 @@ function Format-Result([string]$Result) { return ":x: $($Result.ToLower())" } -# Caraya indents by call depth, and that depth depends on how the suite was -# started (LabVIEWCLI adds its own callers on top). The deepest lines are the -# asserts; the lines one step (two spaces) above them are the tests. +# The report, one line per entry: "