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: " - - ",
+# indented by call depth, two spaces per level. Its structure:
+# * first the callers (LabVIEW CLI's call chain, then Run_Tests_CLI and
+# the suite VI), each line " - ", each at its own depth;
+# * then one line per test, " - :.vi", all at
+# the same depth;
+# * after each test its asserts, one level (two spaces) deeper, with no VI
+# part; an assert's label may itself contain " - ".
+# How deep the tree starts depends on how the suite was started. The assert
+# level is the depth most lines share (each test has at least one assert,
+# each caller line has a depth of its own; on a tie the deeper one), and the
+# tests are one level above it. A line deeper than that belongs to the
+# current test as well, so one deeper line cannot shift the levels.
$entries = @()
-foreach ($line in (Get-Content $ReportPath)) {
+foreach ($line in (Get-Content -LiteralPath $ReportPath -Encoding UTF8)) {
$parts = $line -split ' - ', 3
if ($parts.Count -lt 3) { continue }
$rest = $parts[2]
- $label = $rest.Trim()
- $vi = ''
- $cut = $label.LastIndexOf(' - ')
- if ($cut -ge 0) { $vi = $label.Substring($cut + 3).Trim(); $label = $label.Substring(0, $cut).Trim() }
$entries += [pscustomobject]@{
Indent = $rest.Length - $rest.TrimStart().Length
- Label = $label.TrimEnd(' ', '-')
- Vi = ($vi -replace '^.*:', '')
+ Text = $rest.Trim()
Result = $parts[1].Trim()
}
}
-$assertIndent = ($entries | Measure-Object -Property Indent -Maximum).Maximum
$tests = @()
-$current = $null
-foreach ($entry in $entries) {
- if ($entry.Indent -eq $assertIndent) {
- if ($current) { $current.Asserts += $entry }
- } elseif ($entry.Indent -eq $assertIndent - 2) {
- $current = [pscustomobject]@{ Label = $entry.Label; Vi = $entry.Vi; Result = $entry.Result; Asserts = @() }
- $tests += $current
+if ($entries.Count -gt 0) {
+ $assertIndent = [int]($entries | Group-Object Indent |
+ Sort-Object @{ Expression = 'Count'; Descending = $true }, @{ Expression = { [int]$_.Name }; Descending = $true } |
+ Select-Object -First 1).Name
+ $testIndent = $assertIndent - 2
+ $current = $null
+ foreach ($entry in $entries) {
+ if ($entry.Indent -eq $testIndent) {
+ # " - :": the VI is after the last " - ".
+ $label = $entry.Text
+ $vi = ''
+ $cut = $label.LastIndexOf(' - ')
+ if ($cut -ge 0) { $vi = $label.Substring($cut + 3).Trim(); $label = $label.Substring(0, $cut).Trim() }
+ $current = [pscustomobject]@{ Label = $label.TrimEnd(' ', '-'); Vi = ($vi -replace '^.*:', ''); Result = $entry.Result; Asserts = @() }
+ $tests += $current
+ } elseif ($entry.Indent -gt $testIndent) {
+ if ($current) { $current.Asserts += [pscustomobject]@{ Label = $entry.Text.TrimEnd(' ', '-'); Result = $entry.Result } }
+ } else {
+ # Back above the tests (a caller or suite line): no current test.
+ $current = $null
+ }
}
}
@@ -132,8 +162,10 @@ $open = if ($failed.Count -gt 0) { ' open' } else { '' }
[void]$md.AppendLine('| Test | VI | Result | Checks |')
[void]$md.AppendLine('|---|---|---|---|')
foreach ($test in $tests) {
- $checks = ($test.Asserts | ForEach-Object { "$($_.Label): $($_.Result.ToLower())" }) -join ' '
- [void]$md.AppendLine("| $($test.Label) | ``$($test.Vi)`` | $(Format-Result $test.Result) | $checks |")
+ $checks = ($test.Asserts | ForEach-Object { "$(ConvertTo-MarkdownText $_.Label): $($_.Result.ToLower())" }) -join ' '
+ # In a code span only | needs escaping in a table; a backtick would end it.
+ $vi = $test.Vi.Replace('`', "'").Replace('|', '\|')
+ [void]$md.AppendLine("| $(ConvertTo-MarkdownText $test.Label) | ``$vi`` | $(Format-Result $test.Result) | $checks |")
}
[void]$md.AppendLine()
[void]$md.AppendLine('')
diff --git a/tools/ci/Invoke-CliTest.ps1 b/tools/ci/Invoke-CliTest.ps1
index 4a7e055..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
@@ -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 3dae63d..e68ece6 100644
--- a/tools/ci/LabVIEWCi.psm1
+++ b/tools/ci/LabVIEWCi.psm1
@@ -1,8 +1,8 @@
<#
Shared helpers for the CI scripts: finding the LabVIEW installations on a
-runner, the VI Server port each of them listens on, and the command-line tools
-the workflows call. Used by Resolve-CiEnvironment.ps1, Invoke-CliTest.ps1 and
-New-ViDiffReport.ps1.
+runner, the VI Server port each of them listens on, which LabVIEW CI may
+close, the command-line tools the workflows call and how to run them, and
+Markdown escaping for the reports. Used by the scripts in this folder.
#>
$script:IniSection = 'LabVIEW'
@@ -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]
@@ -112,6 +135,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
@@ -123,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] }
@@ -150,9 +283,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 +309,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 +320,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 +363,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 +371,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 +385,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 {
@@ -260,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
@@ -273,6 +431,107 @@ 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 }
+}
+
+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 = @(& $FilePath @ArgumentList)
+ $code = $LASTEXITCODE
+ } finally {
+ if ($console) { try { [Console]::OutputEncoding = $console } catch { } }
+ }
+ 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 {
+ <# 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
+ 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-Utf8Command, Invoke-Git, ConvertFrom-GitNameStatus, ConvertTo-MarkdownText, Format-MarkdownCodeBlock
diff --git a/tools/ci/New-ViDiffReport.ps1 b/tools/ci/New-ViDiffReport.ps1
index 6ea90e5..e4bd89f 100644
--- a/tools/ci/New-ViDiffReport.ps1
+++ b/tools/ci/New-ViDiffReport.ps1
@@ -51,21 +51,16 @@ $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.
- # 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)
+ 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.
@@ -91,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,16 +102,12 @@ 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
- if ($code -ne 0 -or -not (Test-Path $html) -or -not (Test-Path $list)) {
+ $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 -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
@@ -153,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 })
@@ -169,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' }
@@ -180,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 |  |")
}
[void]$md.AppendLine()
@@ -201,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')
@@ -236,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
@@ -268,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) {
@@ -307,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()
@@ -350,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)
@@ -379,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()
}
@@ -402,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('')
diff --git a/tools/ci/Publish-PrReport.ps1 b/tools/ci/Publish-PrReport.ps1
index 713716a..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(
@@ -23,48 +31,75 @@ 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
$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." }
}
}
@@ -96,47 +131,69 @@ $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.'
}
$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."
diff --git a/tools/ci/README.md b/tools/ci/README.md
index 1cee05a..8b848cc 100644
--- a/tools/ci/README.md
+++ b/tools/ci/README.md
@@ -6,8 +6,8 @@ generated and posted as a comment on the pull request.
| File | Purpose |
|---|---|
-| `Resolve-CiEnvironment.ps1` | First step of every job: finds the LabVIEW for tests and build (oldest ≥ 2020) and for the VI comparison (newest), their VI Server ports, LabVIEW CLI, `vipm` and `gh`; with `-Fix` repairs VI Server settings and port clashes; writes `LABVIEW_*` for the following steps and a table to the job summary. |
-| `LabVIEWCi.psm1` | Functions shared by the scripts here: LabVIEW discovery, VI Server port resolution, tool lookup. |
+| `Resolve-CiEnvironment.ps1` | First step of every job: finds the LabVIEW for tests and build (oldest ≥ 2020) and for the VI comparison (newest), their VI Server ports, LabVIEW CLI, `vipm` and `gh`; with `-Fix` repairs VI Server settings and port clashes, and with `-CleanStart` ends a leftover VIPM Desktop and the job's own LabVIEWs (never another LabVIEW, none with unsaved changes unless `CI_DEDICATED_MACHINE=1`); writes `LABVIEW_*` for the following steps and a table to the job summary. |
+| `LabVIEWCi.psm1` | Functions shared by the scripts here: LabVIEW discovery, VI Server port resolution, which LabVIEW CI may close, tool lookup, running git and other console tools, Markdown escaping. |
| `New-ViDiffReport.ps1` | Compares every changed `.vi`/`.vim`/`.ctl` with its version on the base branch, using LabVIEW's own comparison (`LabVIEWCLI -OperationName CreateComparisonReport`), and writes a Markdown report with before/after images. Added VIs are shown with their block diagram and front panel. Every case frame of the new version of each VI is added in a folded section. |
| `Print Diagram Frames.vi` | Run by `New-ViDiffReport.ps1` through `LabVIEWCLI -OperationName RunVI`: prints one VI with Print.VI To HTML (one picture per case frame) and lists each frame's structure and selector value in print order. Arguments: VI path, HTML file path, frame list path. LabVIEW 20.0. |
| `Invoke-CliTest.ps1` | Runs a test entry VI (`tests\Run_Tests_CLI.vi`, `tests\Run_Protocol_Tests_CLI.vi`) through `LabVIEWCLI -OperationName RunVI`. Exit code 0 passed, 1 tests failed, 2 LabVIEW not reachable (CLI error -350000), 3 entry VI missing on the branch. Used by both workflows. |
@@ -16,9 +16,9 @@ generated and posted as a comment on the pull request.
| `Test-InstalledPackage.ps1` | Tests the package users install: fails on `tools\`, `_ci\`, `tests\`, `.github\`, `builds\`, `.git`, `.ps1` or test-library entries in the `.vip`, installs it with `vipm` into the test LabVIEW, starts the installed Datalogger example (under `\examples\MCP Server`, not the repository's) with `Start VI.vi`, runs `tools\test\Test-McpServer.ps1` against it, closes that LabVIEW and uninstalls the package. Refuses to run when the toolkit is already installed there (`-Force`); `-ContentsOnly` checks only the contents. Test-build job, after the package is uploaded. Closing LabVIEW ends everything running in it: do not point it at a LabVIEW someone works in. |
| `Start VI.vi` | Run by `Test-InstalledPackage.ps1` through `LabVIEWCLI -OperationName RunVI`: opens the VI whose path is its first argument and starts it without waiting (Run VI, Auto Dispose Ref), so the CLI call returns while that VI keeps running. RunVI itself only runs VIs with its own connector pane (error 1031 otherwise). Exit Code 1 when no path is given, the file is missing or the VI is broken. LabVIEW 20.0. |
| `New-SummaryImage.ps1` | Not part of the workflow. Crops a diagram picture (file or URL) to one spot and draws numbered orange boxes around the nodes a pull request's Code summary explains; see `docs/pull-request-reports.md`. |
-| `Publish-PrReport.ps1` | Pushes the diff images to the branch `pr-assets/pr-` and posts or updates one comment on the pull request containing both reports. |
+| `Publish-PrReport.ps1` | Pushes the diff images to the branch `pr-assets/pr-` (with `GH_TOKEN` when the checkout keeps no credentials) and posts one comment on the pull request containing both reports, or updates the one it posted before (found by a hidden marker and its author). |
| `pull-request.workflow.yml` | The GitHub Actions workflow that runs the above and builds a test package. |
-| `release.workflow.yml` | Proposed version of `.github/workflows/release.yml`: runs the Caraya suite and the protocol tests before a build, uses the annotated tag message as release text, writes the `.vipb` as UTF-8 and builds for LabVIEW 2020 64-bit like the pull request builds. |
+| `release.workflow.yml` | Proposed version of `.github/workflows/release.yml`. On every push to `main` and on every tag it runs the Caraya suite and the protocol tests. On a tag it then builds the package, with the test LabVIEW `Resolve-CiEnvironment.ps1` chooses (the oldest LabVIEW of at least 2020, 64-bit preferred), like the pull request builds, and writes the `.vipb` as UTF-8. A `v*` tag sets the package version and must point to a commit on `main`; it creates the GitHub release with the annotated tag message (subject and body, no signature) as release text. A `test-*` tag only uploads the package as an artifact. The build job runs in the `release` environment and is the only job with write access. |
## Activating the workflow
@@ -27,8 +27,20 @@ Copy `pull-request.workflow.yml` to `.github/workflows/pull-request.yml` on
permission that automation tokens for this repository deliberately do not have.
The workflow runs on the self-hosted runner, only for branches of this
-repository (never for forks), and takes the scripts from `main`, so a pull
-request cannot change how its own report is produced.
+repository (never for forks). It takes the report scripts from `main`, so a
+change to them takes effect only once it is merged. That is no isolation: the
+pull request's own VIs, tests, package lists and `tools/test/Test-McpServer.ps1`
+run on the same runner as the same user and could change files, processes or
+the report there. In the first run of a pull request that adds a script `main`
+does not have yet, the pull request's own copy is used. The checkouts keep no
+token (`persist-credentials: false`); only the step that publishes the report
+gets one. That is why only branches of this repository run on the runner.
+
+At the start of each job and when a LabVIEW does not listen on its VI Server
+port, CI force-closes the test and comparison LabVIEWs it chose; no other
+LabVIEW, and none with unsaved changes (a window title with `*`) unless the
+runner's environment has `CI_DEDICATED_MACHINE=1`. See tools/setup/README.md,
+"Self-hosted runner".
Every step runs in Windows PowerShell with `-ExecutionPolicy Bypass`. Each job
starts with `Resolve-CiEnvironment.ps1`, which picks the LabVIEW versions,
@@ -45,6 +57,11 @@ by itself".
the proposed changes applied. Copy it over the live file on `main`. Keep both
copies in step afterwards: the templates are where changes are proposed.
+It expects an environment named `release` (Settings > Environments) with the
+maintainer as required reviewer; GitHub creates a missing environment without
+any protection on the first run, so create it first. A tag ruleset for `v*`
+that only the maintainer may create or move keeps the tag side safe too.
+
## Running locally
```powershell
diff --git a/tools/ci/Resolve-CiEnvironment.ps1 b/tools/ci/Resolve-CiEnvironment.ps1
index 8fa8c08..a1ac912 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
@@ -98,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
@@ -117,11 +124,11 @@ 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.')
}
-$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) {
@@ -139,10 +146,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 +160,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 +208,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,
@@ -243,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
@@ -266,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 421f305..a268467 100644
--- a/tools/ci/Test-InstalledPackage.ps1
+++ b/tools/ci/Test-InstalledPackage.ps1
@@ -75,36 +75,34 @@ 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
}
+# 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
@@ -126,7 +124,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"
}
@@ -270,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/ci/pull-request.workflow.yml b/tools/ci/pull-request.workflow.yml
index 7d4a04c..7943abe 100644
--- a/tools/ci/pull-request.workflow.yml
+++ b/tools/ci/pull-request.workflow.yml
@@ -8,6 +8,12 @@ name: Pull Request Review
#
# Lives in tools/ci as pull-request.workflow.yml; copy it to
# .github/workflows/pull-request.yml on main to activate it.
+#
+# Values from the event or from earlier steps reach the scripts through env:,
+# never pasted into a run: block with ${{ }}, so a branch name or a step
+# output cannot change the script. Files the runner reads after a step
+# (GITHUB_OUTPUT, GITHUB_ENV, GITHUB_STEP_SUMMARY) are written as UTF-8
+# without BOM.
on:
pull_request:
@@ -66,18 +72,24 @@ jobs:
contents: write # pushes the diff images to pr-assets/pr-
pull-requests: write # posts the report comment
steps:
+ # persist-credentials: false leaves no token in .git/config, where the
+ # pull request's own code (tests, VIs, the protocol tester) could read
+ # it. Only the step that publishes the report gets the token, as
+ # GH_TOKEN; Publish-PrReport.ps1 pushes with it.
- name: Checkout Pull Request
- uses: actions/checkout@v4
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
fetch-depth: 0 # the diff needs the history of both branches
+ persist-credentials: false
# The report scripts come from main, not from the pull request, so a
- # pull request cannot change how its own report is produced.
+ # change to them takes effect only once it is merged.
- name: Checkout Report Scripts from main
- uses: actions/checkout@v4
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
ref: ${{ github.event.pull_request.base.ref }}
path: _ci
+ persist-credentials: false
sparse-checkout: |
tools/ci
tools/setup
@@ -86,14 +98,16 @@ jobs:
# VI Server ports and the tools, repairs what is easy to repair (VI
# Server off, port clashes, leftover LabVIEW CLI processes, and with
# -CleanStart a VIPM Desktop left over from an earlier job together with
- # the LabVIEWs it was driving) and lists it
- # all in the job summary. See the comment at env above.
+ # the test and comparison LabVIEWs it was driving, never another LabVIEW
+ # and none with unsaved changes unless CI_DEDICATED_MACHINE=1) and lists
+ # it all in the job summary. See the comment at env above.
# The scripts come from main. While main does not have the scripts this
# workflow calls yet (in the run of the pull request that introduces
# them), this run uses the pull request's own tools\ci and tools\setup
# instead, with a warning; this job only runs for branches of this
# repository. Later steps then call the same copies through _ci.
- name: Find LabVIEW and Tools
+ id: setup
run: |
$ci = "$env:GITHUB_WORKSPACE\_ci"
if (-not (Test-Path "$ci\tools\ci\Resolve-CiEnvironment.ps1")) {
@@ -114,6 +128,7 @@ jobs:
# that are already installed. VIPM Desktop must have detected the
# LabVIEW installations once (see tools/setup/README.md).
- name: Install VIPM Dependencies
+ id: install
timeout-minutes: 45
run: |
$install = "$env:GITHUB_WORKSPACE\_ci\tools\setup\Install-Dependencies.ps1"
@@ -127,9 +142,15 @@ jobs:
# ports again, so the tests and the diff reach the LabVIEW they mean;
# the values written here replace the ones from the first check.
- name: Check LabVIEW after Package Install
+ id: recheck
run: |
& "$env:GITHUB_WORKSPACE\_ci\tools\ci\Resolve-CiEnvironment.ps1" -For All -Fix
+ # The steps below run only when the three steps above succeeded (the
+ # default condition, or an explicit check of their outcome), so none of
+ # them runs with empty LABVIEW_* values; a step that did not run is
+ # reported as "not run" in the report and by the last step.
+
# The suite runs only the tests Test_MCP_Server.vi calls. Fails when a
# "test *.vi" of the test library is not called, so a test that was
# added but not wired in is not skipped without notice. Reads files
@@ -158,14 +179,14 @@ jobs:
-VIPath "$env:GITHUB_WORKSPACE\tests\Run_Tests_CLI.vi" `
-LabVIEWPath "$env:LABVIEW_PATH" -PortNumber $env:LABVIEW_PORT
$status = $LASTEXITCODE
- "status=$status" >> $env:GITHUB_OUTPUT
+ [System.IO.File]::AppendAllText($env:GITHUB_OUTPUT, "status=$status`n")
if ($status -ne 0) { exit 1 }
# Starts the toolkit's test server and runs tools\test\Test-McpServer.ps1
# against it over HTTP. Skipped when LabVIEW was not reachable above.
- name: Run Protocol Tests
id: protocol
- if: always() && steps.tests.outputs.status != '2'
+ if: ${{ !cancelled() && steps.recheck.outcome == 'success' && steps.tests.outputs.status != '2' }}
continue-on-error: true
run: |
$report = "$env:GITHUB_WORKSPACE\tests\results\protocol-report.txt"
@@ -174,40 +195,55 @@ jobs:
-VIPath "$env:GITHUB_WORKSPACE\tests\Run_Protocol_Tests_CLI.vi" `
-LabVIEWPath "$env:LABVIEW_PATH" -PortNumber $env:LABVIEW_PORT
$status = $LASTEXITCODE
- "status=$status" >> $env:GITHUB_OUTPUT
+ [System.IO.File]::AppendAllText($env:GITHUB_OUTPUT, "status=$status`n")
# A branch without the entry VI is not a failure.
if ($status -ne 0 -and $status -ne 3) { exit 1 }
exit 0
+ # A skipped test step becomes "not-run" in the report. A protocol step
+ # skipped because LabVIEW was not reachable (status 2) gets no section,
+ # as the test section already says so.
- name: Build Test Report
- if: always()
+ if: ${{ !cancelled() }}
+ env:
+ TESTS_OUTCOME: ${{ steps.tests.outcome }}
+ TESTS_STATUS: ${{ steps.tests.outputs.status }}
+ PROTOCOL_OUTCOME: ${{ steps.protocol.outcome }}
+ PROTOCOL_STATUS: ${{ steps.protocol.outputs.status }}
run: |
+ $testStatus = if ($env:TESTS_OUTCOME -eq 'skipped') { 'not-run' } else { $env:TESTS_STATUS }
+ $protocolStatus = if ($env:PROTOCOL_OUTCOME -eq 'skipped' -and $env:TESTS_STATUS -ne '2') { 'not-run' } else { $env:PROTOCOL_STATUS }
& "$env:GITHUB_WORKSPACE\_ci\tools\ci\Convert-CarayaReport.ps1" `
-ReportPath "$env:GITHUB_WORKSPACE\tests\results\caraya-report.txt" `
-OutFile "$env:RUNNER_TEMP\test-report.md" `
- -TestStatus "${{ steps.tests.outputs.status }}" `
+ -TestStatus $testStatus `
-ProtocolReportPath "$env:GITHUB_WORKSPACE\tests\results\protocol-report.txt" `
- -ProtocolStatus "${{ steps.protocol.outputs.status }}"
- Get-Content "$env:RUNNER_TEMP\test-report.md" | Add-Content $env:GITHUB_STEP_SUMMARY
+ -ProtocolStatus $protocolStatus
+ [System.IO.File]::AppendAllText($env:GITHUB_STEP_SUMMARY, [System.IO.File]::ReadAllText("$env:RUNNER_TEMP\test-report.md"))
# Exits 1 when a changed VI could not be compared (LabVIEW not
# reachable, comparison error). The report is still written and posted;
- # the last step then fails the run.
+ # the last step then fails the run. Needs the comparison LabVIEW from
+ # the first step; it also runs when the package install failed (the
+ # diagrams then show "?" for missing subVIs), but not when the check
+ # after the install failed.
- name: Build VI Diff Report
id: diff
- if: always()
+ if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.recheck.outcome != 'failure' }}
continue-on-error: true
+ env:
+ BASE_REF: ${{ github.event.pull_request.base.ref }}
run: |
& "$env:GITHUB_WORKSPACE\_ci\tools\ci\New-ViDiffReport.ps1" `
- -BaseRef "origin/${{ github.event.pull_request.base.ref }}" `
+ -BaseRef "origin/$env:BASE_REF" `
-HeadDir "$env:GITHUB_WORKSPACE" `
-OutDir "$env:RUNNER_TEMP\vi-diff" `
-LabVIEWPath "$env:LABVIEW_COMPARE_PATH" -PortNumber $env:LABVIEW_COMPARE_PORT
exit $LASTEXITCODE
- name: Upload Reports
- if: always()
- uses: actions/upload-artifact@v4
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: review-reports-pr-${{ github.event.pull_request.number }}
path: |
@@ -215,30 +251,54 @@ jobs:
${{ runner.temp }}/vi-diff
retention-days: 14
+ # The only step with the token: Publish-PrReport.ps1 pushes the images
+ # with it (the checkout keeps no credentials) and posts the comment.
- name: Post Report on the Pull Request
- if: always()
+ if: ${{ !cancelled() }}
env:
GH_TOKEN: ${{ github.token }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ DIFF_OUTCOME: ${{ steps.diff.outcome }}
run: |
- $runUrl = "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
+ $runUrl = "$env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID"
+ $footer = "Report for commit $env:HEAD_SHA. The installable test package is under Artifacts of [this run]($runUrl) once the build job has finished."
+ if ($env:DIFF_OUTCOME -eq 'skipped') {
+ $footer = "**VI diff: not run**, because finding LabVIEW and the tools failed; see [this run]($runUrl).`n`n" + $footer
+ }
& "$env:GITHUB_WORKSPACE\_ci\tools\ci\Publish-PrReport.ps1" `
- -PrNumber ${{ github.event.pull_request.number }} `
- -Repo "${{ github.repository }}" `
+ -PrNumber $env:PR_NUMBER `
+ -Repo "$env:GITHUB_REPOSITORY" `
-RepoDir "$env:GITHUB_WORKSPACE" `
-TestReport "$env:RUNNER_TEMP\test-report.md" `
-DiffDir "$env:RUNNER_TEMP\vi-diff" `
- -Footer "Report for commit ${{ github.event.pull_request.head.sha }}. The installable test package is under Artifacts of [this run]($runUrl) once the build job has finished."
+ -Footer $footer
- name: Fail if the Tests or the VI Diff Failed
- if: steps.tests.outcome == 'failure' || steps.protocol.outcome == 'failure' || steps.diff.outcome == 'failure' || steps.wired.outcome == 'failure'
+ if: ${{ !cancelled() && (steps.setup.outcome != 'success' || steps.install.outcome != 'success' || steps.recheck.outcome != 'success' || steps.tests.outcome == 'failure' || steps.protocol.outcome == 'failure' || steps.diff.outcome != 'success' || steps.wired.outcome == 'failure') }}
+ env:
+ SETUP_OUTCOME: ${{ steps.setup.outcome }}
+ INSTALL_OUTCOME: ${{ steps.install.outcome }}
+ RECHECK_OUTCOME: ${{ steps.recheck.outcome }}
+ TESTS_OUTCOME: ${{ steps.tests.outcome }}
+ TESTS_STATUS: ${{ steps.tests.outputs.status }}
+ PROTOCOL_OUTCOME: ${{ steps.protocol.outcome }}
+ DIFF_OUTCOME: ${{ steps.diff.outcome }}
+ WIRED_OUTCOME: ${{ steps.wired.outcome }}
run: |
- if ("${{ steps.tests.outputs.status }}" -eq '2') {
+ function Format-Outcome([string]$Outcome) { if ($Outcome -eq 'skipped' -or -not $Outcome) { 'not run' } else { $Outcome } }
+ if ($env:SETUP_OUTCOME -ne 'success' -or $env:INSTALL_OUTCOME -ne 'success' -or $env:RECHECK_OUTCOME -ne 'success') {
+ Write-Host "::error::Finding LabVIEW and tools: $(Format-Outcome $env:SETUP_OUTCOME), package install: $(Format-Outcome $env:INSTALL_OUTCOME), check after the install: $(Format-Outcome $env:RECHECK_OUTCOME). The steps that need them did not run."
+ }
+ if ($env:TESTS_STATUS -eq '2') {
Write-Host "::error::LabVIEW was not reachable on port $env:LABVIEW_PORT; no tests ran."
}
- if ("${{ steps.diff.outcome }}" -eq 'failure') {
+ if ($env:DIFF_OUTCOME -eq 'failure') {
Write-Host "::error::The VI diff could not be produced for every changed VI (LabVIEW $env:LABVIEW_COMPARE_PATH, port $env:LABVIEW_COMPARE_PORT). A pull request needs it; see the report."
+ } elseif ($env:DIFF_OUTCOME -ne 'success') {
+ Write-Host "::error::The VI diff did not run. A pull request needs it."
}
- Write-Host "::error::Caraya suite: ${{ steps.tests.outcome }}, protocol tests: ${{ steps.protocol.outcome }}, VI diff: ${{ steps.diff.outcome }}, test wiring: ${{ steps.wired.outcome }}."
+ Write-Host "::error::Caraya suite: $(Format-Outcome $env:TESTS_OUTCOME), protocol tests: $(Format-Outcome $env:PROTOCOL_OUTCOME), VI diff: $(Format-Outcome $env:DIFF_OUTCOME), test wiring: $(Format-Outcome $env:WIRED_OUTCOME)."
exit 1
# ==========================================
@@ -246,18 +306,24 @@ jobs:
# ==========================================
test-build:
needs: review
+ # Same fork guard as the review job, stated here too so this job never
+ # runs code of a fork on the self-hosted runner, whatever "needs" does.
+ if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: self-hosted
permissions:
contents: read
steps:
- name: Checkout Pull Request
- uses: actions/checkout@v4
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ persist-credentials: false
- name: Checkout Report Scripts from main
- uses: actions/checkout@v4
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
ref: ${{ github.event.pull_request.base.ref }}
path: _ci
+ persist-credentials: false
sparse-checkout: tools/ci
# Same choice of LabVIEW as in the review job (a job starts with a fresh
@@ -284,6 +350,8 @@ jobs:
# them; with 600 s the build failed or passed depending on a few
# seconds. 25 minutes of silence still ends a VIPM that really hangs.
VIPM_DESKTOP_LIVELINESS_TIMEOUT: 1500
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
$vipbFile = "$env:GITHUB_WORKSPACE\src\LabVIEW MCP Server SDK.vipb"
# Read and write the .vipb as UTF-8: VIPM rejects a file that is not valid UTF-8.
@@ -292,11 +360,11 @@ jobs:
# Keep major.minor.patch from the .vipb and use the run number as the
# build number, so every test build gets its own installable version.
$current = ($vipbContent | Select-String "(\d+)\.(\d+)\.(\d+)\.\d+ ").Matches[0]
- $newVersion = "$($current.Groups[1].Value).$($current.Groups[2].Value).$($current.Groups[3].Value).${{ github.run_number }}"
+ $newVersion = "$($current.Groups[1].Value).$($current.Groups[2].Value).$($current.Groups[3].Value).$env:GITHUB_RUN_NUMBER"
Write-Host "Test build version: $newVersion"
$vipbContent = $vipbContent -replace ".*? ", "$newVersion "
- $notes = "Test build of pull request #${{ github.event.pull_request.number }} (commit ${{ github.event.pull_request.head.sha }}). Not a release."
+ $notes = "Test build of pull request #$env:PR_NUMBER (commit $env:HEAD_SHA). Not a release."
$vipbContent = $vipbContent -replace ".*? ", "$notes "
[System.IO.File]::WriteAllLines($vipbFile, $vipbContent, (New-Object System.Text.UTF8Encoding $false))
@@ -310,7 +378,7 @@ jobs:
Write-Error "VIPM CLI build failed with exit code $LASTEXITCODE."
exit 1
}
- "### Test package built: version $newVersion" >> $env:GITHUB_STEP_SUMMARY
+ [System.IO.File]::AppendAllText($env:GITHUB_STEP_SUMMARY, "### Test package built: version $newVersion`n")
- name: Locate Built VIP Artifact
run: |
@@ -320,10 +388,10 @@ jobs:
Sort-Object LastWriteTime -Descending | Select-Object -First 1
if (-not $vipFile) { Write-Host '::error::The build produced no .vip file.'; exit 1 }
Write-Host "Package: $($vipFile.FullName)"
- echo "VIP_PATH=$($vipFile.FullName)" >> $env:GITHUB_ENV
+ [System.IO.File]::AppendAllText($env:GITHUB_ENV, "VIP_PATH=$($vipFile.FullName)`n")
- name: Upload Test Package
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: test-vip-package-pr-${{ github.event.pull_request.number }}
path: ${{ env.VIP_PATH }}
@@ -344,12 +412,12 @@ jobs:
run: |
$script = "$env:GITHUB_WORKSPACE\_ci\tools\ci\Test-InstalledPackage.ps1"
if (-not (Test-Path $script)) { $script = "$env:GITHUB_WORKSPACE\tools\ci\Test-InstalledPackage.ps1" }
+ $reportFile = "$env:RUNNER_TEMP\installed-package-report.txt"
& $script -VipPath "$env:VIP_PATH" -RepoDir "$env:GITHUB_WORKSPACE" `
-LabVIEWPath "$env:LABVIEW_PATH" -PortNumber $env:LABVIEW_PORT `
- -ReportFile "$env:RUNNER_TEMP\installed-package-report.txt"
+ -ReportFile $reportFile
$status = $LASTEXITCODE
- '### Installed package test' >> $env:GITHUB_STEP_SUMMARY
- '```' >> $env:GITHUB_STEP_SUMMARY
- Get-Content "$env:RUNNER_TEMP\installed-package-report.txt" -ErrorAction SilentlyContinue | Add-Content $env:GITHUB_STEP_SUMMARY
- '```' >> $env:GITHUB_STEP_SUMMARY
- exit $status
\ No newline at end of file
+ $report = if (Test-Path $reportFile) { [System.IO.File]::ReadAllText($reportFile).TrimEnd() } else { '(no report written)' }
+ $fence = '````'
+ [System.IO.File]::AppendAllText($env:GITHUB_STEP_SUMMARY, "### Installed package test`n$fence`n$report`n$fence`n")
+ exit $status
diff --git a/tools/ci/release.workflow.yml b/tools/ci/release.workflow.yml
index 2e36325..7f8f929 100644
--- a/tools/ci/release.workflow.yml
+++ b/tools/ci/release.workflow.yml
@@ -8,8 +8,9 @@ on:
- 'v*.*.*'
- 'test-*'
+# Read-only by default; only the job that creates the release may write.
permissions:
- contents: write
+ contents: read
# Every run step goes through Windows PowerShell with the execution policy
# bypassed for that process only, so the runner needs no Set-ExecutionPolicy.
@@ -39,7 +40,7 @@ jobs:
timeout-minutes: 60
steps:
- name: Checkout Source Code
- uses: actions/checkout@v4
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- name: Find LabVIEW and Tools
run: |
@@ -86,13 +87,41 @@ jobs:
needs: test # <--- This is the magic line. It waits for JOB 1.
if: startsWith(github.ref, 'refs/tags/') # <--- Only build if it's a tag!
runs-on: self-hosted
-
+ # The "release" environment holds the job until a required reviewer
+ # (the maintainer) approves it, and its deployment rules can limit it to
+ # v* tags. The environment is created in the repository settings.
+ environment: release
+ permissions:
+ contents: write # creates the GitHub release and uploads the .vip
+
steps:
- name: Checkout Source Code
- uses: actions/checkout@v4
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
+ fetch-depth: 0 # the check below needs the history of main
fetch-tags: true # <--- CRITICAL: Tells GitHub to download the tag annotations!
+ # A release is built only from a commit that is on main, that is one
+ # that went through a reviewed pull request: a v* tag on any other
+ # commit fails here, before anything is built. test-* tags build a
+ # test package only (no release) and may point anywhere.
+ - name: Check that the Tag Is on main
+ if: startsWith(github.ref, 'refs/tags/v')
+ env:
+ TAG_NAME: ${{ github.ref_name }}
+ run: |
+ git fetch --quiet --no-tags origin "+refs/heads/main:refs/remotes/origin/main"
+ if ($LASTEXITCODE -ne 0) { Write-Host '::error::Could not fetch main from origin.'; exit 1 }
+ $commit = (git rev-parse HEAD).Trim()
+ git merge-base --is-ancestor $commit refs/remotes/origin/main
+ $code = $LASTEXITCODE
+ if ($code -eq 1) {
+ Write-Host "::error::Tag $env:TAG_NAME points to $commit, which is not on main. Releases are built only from commits on main."
+ exit 1
+ }
+ if ($code -ne 0) { Write-Host "::error::git merge-base --is-ancestor failed with exit code $code."; exit 1 }
+ Write-Host "Tag $env:TAG_NAME ($commit) is on main."
+
# Same LabVIEW as the test job (a job starts with a fresh environment).
- name: Find LabVIEW and Tools
run: |
@@ -110,24 +139,32 @@ jobs:
# seconds. 25 minutes of silence still ends a VIPM that really hangs.
VIPM_DESKTOP_LIVELINESS_TIMEOUT: 1500
# Passed through the environment, not pasted into the script: a
- # commit message with quotes or $ would otherwise break or change it.
+ # commit message or tag name with quotes or $ would otherwise break
+ # or change it.
HEAD_COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
+ TAG_NAME: ${{ github.ref_name }}
run: |
$vipbFile = "$env:GITHUB_WORKSPACE\src\LabVIEW MCP Server SDK.vipb"
-
- $gitTag = "${{ github.ref_name }}"
+ # git writes UTF-8; without this Windows PowerShell reads a tag
+ # message in the console code page and garbles non-ASCII text.
+ try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false } catch { }
+
+ $gitTag = $env:TAG_NAME
Write-Host "Detected Tag: $gitTag"
-
+
# 1. Extract the Annotated Tag Message using the Git CLI.
# actions/checkout recreates the tag as a lightweight tag on the
# commit, so %(contents) would return the commit message. Fetch
# the real tag object first.
git fetch --quiet --force --no-tags origin "refs/tags/${gitTag}:refs/tags/${gitTag}"
+ if ($LASTEXITCODE -ne 0) { Write-Error "Fetching tag $gitTag failed."; exit 1 }
$tagMsg = ""
if ((git cat-file -t "refs/tags/$gitTag") -eq "tag") {
- $tagMsg = (git tag -l --format='%(contents)' $gitTag) -join "`n"
+ # Subject and body only: %(contents) would also include the
+ # signature block of a signed tag.
+ $tagMsg = ((git tag -l --format='%(contents:subject)%0a%0a%(contents:body)' $gitTag) -join "`n").Trim()
}
-
+
# 2. Fallback to the commit message if the tag was left blank
if ([string]::IsNullOrWhiteSpace($tagMsg)) {
$tagMsg = "$env:HEAD_COMMIT_MESSAGE"
@@ -135,36 +172,38 @@ jobs:
} else {
Write-Host "Found annotated tag message!"
}
-
+
Write-Host "Release Notes to use:`n$tagMsg"
# Hand the same text to the GitHub release step (UTF-8 without BOM)
$notesFile = Join-Path $env:RUNNER_TEMP "release-notes.md"
[System.IO.File]::WriteAllText($notesFile, $tagMsg, (New-Object System.Text.UTF8Encoding $false))
-
+
# 3. Update the Version Number (Only if it's a 'v' release tag)
# Read and write the .vipb as UTF-8: VIPM rejects a file that is not
# valid UTF-8, and Get-Content/Set-Content use the ANSI code page in
# Windows PowerShell.
$vipbContent = [System.IO.File]::ReadAllLines($vipbFile)
-
- if ($gitTag -match "v?(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?") {
+
+ # Anchored: a test-* tag that contains a number (test-1.2.3) keeps
+ # the version of the .vipb.
+ if ($gitTag -match '^v(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?$') {
$major = $matches[1]
$minor = $matches[2]
$patch = $matches[3]
$build = if ($matches[4]) { $matches[4] } else { 0 }
-
+
$newVersion = "$major.$minor.$patch.$build"
Write-Host "Updating VIPB to version: $newVersion"
$vipbContent = $vipbContent -replace ".*? ", "$newVersion "
}
-
+
# 4. Inject the Release Notes into the VIPB
# -replace reads $_, $& and $1 in the replacement text as
# substitutions, so double every $ to keep the message as written.
$safeMsg = [System.Security.SecurityElement]::Escape($tagMsg).Replace('$', '$$')
$vipbContent = $vipbContent -replace ".*? ", "$safeMsg "
-
+
[System.IO.File]::WriteAllLines($vipbFile, $vipbContent, (New-Object System.Text.UTF8Encoding $false))
# 5. Run the build with the LabVIEW chosen above (as the pull request
@@ -172,7 +211,7 @@ jobs:
# version; the step above warns when that is not LabVIEW 2020 64-bit.
Write-Host "Building VI Package with LabVIEW $env:LABVIEW_VERSION $env:LABVIEW_BITNESS-bit..."
vipm build "$vipbFile" --labview-version $env:LABVIEW_VERSION --labview-bitness $env:LABVIEW_BITNESS
-
+
if ($LASTEXITCODE -ne 0) {
Write-Error "VIPM CLI build failed with exit code $LASTEXITCODE."
exit 1
@@ -187,18 +226,19 @@ jobs:
Sort-Object LastWriteTime -Descending | Select-Object -First 1
if (-not $vipFile) { Write-Host '::error::The build produced no .vip file.'; exit 1 }
Write-Host "Package: $($vipFile.FullName)"
- echo "VIP_PATH=$($vipFile.FullName)" >> $env:GITHUB_ENV
+ # UTF-8 without BOM, which the runner reads (">>" writes UTF-16).
+ [System.IO.File]::AppendAllText($env:GITHUB_ENV, "VIP_PATH=$($vipFile.FullName)`n")
- name: Upload Artifact for Testing
if: ${{ !startsWith(github.ref, 'refs/tags/v') }}
- uses: actions/upload-artifact@v4
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: test-vip-package
path: ${{ env.VIP_PATH }}
- name: Create GitHub Release and Upload VIP
if: startsWith(github.ref, 'refs/tags/v')
- uses: softprops/action-gh-release@v2
+ uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2
with:
files: ${{ env.VIP_PATH }}
body_path: ${{ runner.temp }}/release-notes.md
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."
diff --git a/tools/setup/README.md b/tools/setup/README.md
index 410713f..9863071 100644
--- a/tools/setup/README.md
+++ b/tools/setup/README.md
@@ -72,7 +72,7 @@ would use there (without `-Fix` it changes nothing):
|---|---|---|
| LabVIEW for tests and build | repository variable `LABVIEW_PATH` if that file exists, otherwise the **oldest** LabVIEW of at least 2020 in the default folders or the registry, 64-bit preferred. The package is built with it, so its version is the package's minimum LabVIEW version; anything other than 2020 64-bit gives a warning | - |
| LabVIEW for the VI comparison | `LABVIEW_COMPARE_PATH` if it exists, otherwise the **newest** LabVIEW, 32-bit preferred at equal version; warns when it is older than the LabVIEW CLI | - |
-| VI Server port of each | the port the running LabVIEW listens on, else `server.tcp.port` in its `LabVIEW.ini`, else `LABVIEW_PORT` / `LABVIEW_COMPARE_PORT`, else 3363 | VI Server switched on; a missing port written; a port held by another program, or by the other LabVIEW, moved to a free one; localhost added to `server.tcp.access` if it is missing; a LabVIEW that runs without listening on its port is closed so LabVIEW CLI restarts it |
+| VI Server port of each | VIPM's port for that LabVIEW (`[Targets]` in `C:\ProgramData\JKI\VIPM\Settings.ini`) unless another LabVIEW is meant to have it, else `server.tcp.port` in its `LabVIEW.ini`, else `LABVIEW_PORT` / `LABVIEW_COMPARE_PORT`, else 3363. A running LabVIEW that listens on that port is used as it is; without `-Fix`, one that listens on its `LabVIEW.ini` port or the requested port instead is used on that port | VI Server switched on; the port written to `LabVIEW.ini`; a port held by another program, or meant for another LabVIEW, moved to the next free one; localhost added to `server.tcp.access` if it is missing; a test or comparison LabVIEW that runs on another port or none is force-closed so LabVIEW CLI restarts it with these settings, unless it has unsaved changes (see "Self-hosted runner") |
| LabVIEW CLI, `vipm`, `gh` | `PATH`, then their default install folders, which are then added to `PATH` | LabVIEW CLI processes left from a cancelled run are ended |
When LabVIEW CLI still cannot connect (error -350000), the test and diff
@@ -86,9 +86,12 @@ or port; a value that does not fit the runner is reported and replaced.
## VI Server port
VIPM gives every LabVIEW installation its own VI Server TCP port when it first
-connects (written to that LabVIEW's `LabVIEW.ini` as `server.tcp.port`). The
-LabVIEW CLI must be given the same port, which CI reads from there (see
-above). To look it up by hand:
+connects. It records the port in its own settings (`[Targets]` in
+`C:\ProgramData\JKI\VIPM\Settings.ini`), writes it to that LabVIEW's
+`LabVIEW.ini` as `server.tcp.port`, and puts LabVIEW back on it whenever VIPM
+starts that LabVIEW. The LabVIEW CLI must be given the same port. CI takes
+VIPM's port first and the `LabVIEW.ini` port only when VIPM has none for that
+LabVIEW (see the table above). To look it up by hand:
```powershell
Select-String 'server.tcp.port' "C:\Program Files\National Instruments\LabVIEW 2020\LabVIEW.ini"
@@ -141,13 +144,16 @@ sources are saved without compiled code, so LabVIEW keeps it in a per-user
cache). Rebuild it once by mass compiling the checkout:
```powershell
+git status
LabVIEWCLI -OperationName MassCompile -DirectoryToCompile "$PWD\tests" `
-LabVIEWPath "C:\Program Files\National Instruments\LabVIEW 2020\LabVIEW.exe" -PortNumber
-git checkout -- .
+git restore -- tests
```
-The three `fake ... broken vi.vi` files are reported as bad on purpose; the
-`git checkout` undoes the files the mass compile saved.
+The three `fake ... broken vi.vi` files are reported as bad on purpose. The
+mass compile saves the VIs it recompiles, and `git restore -- tests` undoes
+that, but it also discards any change of your own below `tests`: check
+`git status` first and commit or stash such changes before you start.
## Self-hosted runner
@@ -160,3 +166,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.