diff --git a/CHANGELOG.md b/CHANGELOG.md index 0733983..96abd89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.3.0] - 2026-11-22 + +This minor release adds Windows-only support for legacy .NET Framework target frameworks (`net471`, `net472`, `net48`, `net481`) across both `console` and `test` modes, while preserving manifest `schemaVersion` 1 and existing modern .NET execution behavior. + +### Added + +- Added Windows-only support for legacy .NET Framework TFMs (`net471`, `net472`, `net48`, `net481`) in `csrun.ps1`, bypassing the .NET Core release index, SDK channel check, and `--list-runtimes` check while still building with a selected .NET 10+ SDK and failing fast on non-Windows platforms and inside Linux containers, +- Added an isolated temporary SDK-style `.csproj` fallback in `console` mode for `.NET Framework` targets (since `dotnet run --file` does not support `.NET Framework` TFMs directly), stripping validated matching preamble directives via `Get-ConsoleSource -StripDirectives`, configuring `LangVersion=latest` and `Microsoft.NETFramework.ReferenceAssemblies@1.0.3` (`PrivateAssets="All"` unless already pinned in `dependsOn`) for both `console` and `test` `.NET Framework` projects, and cleaning up the temporary directory in `finally`, +- Added unit, integration, and container test coverage in `tests/csrun.Tests.ps1` and `tests/container.Tests.ps1` for `net471`–`net481` validation, rejection of unsupported TFMs (`netstandard2.0`, `net45`, `net46`, `net461`, `net462`, `net47`, `net482`, `net48-windows`), non-Windows and Linux-container rejection, `net48` console and xUnit v3 execution against `lib/netstandard2.0` package assets with exit-status and stderr preservation, and preamble directive matching/conflict handling, +- Added documentation in `README.md` covering Windows-only `net471`–`net481` support, release-index/runtime-list bypass, non-executable TFM rejection, temporary `.csproj` fallback, and `test` mode `.NET Framework` project configuration. + +### Changed + +- Generalized `Write-TestProject` to `Write-Project` in `csrun.ps1`, adding `WarningsAsErrors=NU1603;NU1605` to generated `.csproj` files and passing `--framework` to `dotnet run --project` in `test` mode. + ## [0.2.2] - 2026-11-18 This patch release extends Docker publishing with release-versioned SDK aliases alongside the existing movable convenience tags. The standalone native PowerShell engine (`csrun.ps1`), manifest schema version 1 and container execution contract remain unchanged. @@ -58,6 +73,7 @@ This is the first release that introduces csrun as a standalone PowerShell scrip - Added pull request and tag release workflows that run the test suite on Windows with the .NET 11 SDK and a .NET 10 compatibility job, then create a draft GitHub release with the tested `csrun.ps1` attached, - Added the MIT license. +[0.3.0]: https://github.com/codebeltnet/csrun/compare/v0.2.2...v0.3.0 [0.2.2]: https://github.com/codebeltnet/csrun/compare/v0.2.1...v0.2.2 [0.2.1]: https://github.com/codebeltnet/csrun/compare/v0.2.0...v0.2.1 [0.2.0]: https://github.com/codebeltnet/csrun/compare/v0.1.0...v0.2.0 diff --git a/README.md b/README.md index f733c3b..4cd2d2f 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ Direct options default to `console`, the latest supported GA LTS framework, and | --- | --- | | `schemaVersion` | Required integer `1`. | | `mode` | Required `console` or `test`, case-insensitive. | -| `framework` | Optional .NET 10+ TFM such as `net11.0` or `net11.0-windows`. Omission selects the highest supported GA LTS channel; an explicit value is preserved and must identify a supported GA LTS or STS channel or the latest preview/go-live channel. RIDs such as `win-x64` are invalid. Platform availability is checked by the SDK. | +| `framework` | Optional .NET 10+ TFM such as `net11.0` or `net11.0-windows`, or a legacy .NET Framework TFM (`net471`, `net472`, `net48`, `net481`) natively on Windows only. Omission selects the highest supported GA LTS channel; an explicit modern .NET value is preserved and must identify a supported GA LTS or STS channel or the latest preview/go-live channel. Legacy .NET Framework targets fail fast on Linux/macOS and inside Linux containers. RIDs such as `win-x64` and non-executable TFMs such as `netstandard2.0` are invalid. Platform availability is checked by the SDK. | | `source` | Required nonempty string containing a complete program or test source. Multiline text, quotes, Unicode, and line endings are preserved. | | `dependsOn` | Optional array of `PackageId@ExactVersion` pins, including prereleases. Identical duplicates collapse; conflicting versions, ranges, wildcards, and unversioned packages fail. Use three or four numeric version components. | | `sdk` | Optional `Microsoft.NET.Sdk` (default) or `Microsoft.NET.Sdk.Web`. Never inferred. | @@ -120,13 +120,13 @@ Direct options default to `console`, the latest supported GA LTS framework, and Unknown fields are rejected to expose misspellings. No package discovery, source wrapping, method mode, or source rewriting occurs. Ordinary transitive NuGet dependencies still resolve normally. Source-only methods without a runnable entry point produce the actual compiler error. -Both modes validate the target against Microsoft's [release index](https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json), cached for up to 12 hours. If the index and a recent valid cache are unavailable, execution fails. An explicit preview target is the opt-in; no automatic fallback occurs when the default LTS cannot run. The selected SDK follows `global.json`, must be .NET 10 or newer, and must support the target. A newer SDK can build an older supported target. The corresponding .NET runtime and any required ASP.NET shared framework must be installed; csrun installs neither. Platform-specific build requirements are checked by the SDK. +Both modes validate modern .NET targets against Microsoft's [release index](https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json), cached for up to 12 hours. If the index and a recent valid cache are unavailable, execution fails. An explicit preview target is the opt-in; no automatic fallback occurs when the default LTS cannot run. Legacy .NET Framework targets (`net471`–`net481`) bypass the .NET Core release index and runtime list, require Windows natively, and still build using the selected .NET 10+ SDK. The selected SDK follows `global.json`, must be .NET 10 or newer, and must support the target. A newer SDK can build an older supported target. For modern .NET targets, the corresponding .NET runtime and any required ASP.NET shared framework must be installed; csrun installs neither. Platform-specific build requirements are checked by the SDK. -Console mode prepends SDK, target framework, and pinned package directives to the source stream and invokes `dotnet run -`. If a current-directory project exists, SDK 11 would select it first; csrun instead uses an isolated temporary `.cs` file and `dotnet run --file` to force file-based execution while retaining the program's working directory. It creates no console project. The SDK manages its own normal build cache. Approximate NuGet matches and downgrades are errors, preventing an unavailable pin from silently becoming another version. +Console mode prepends SDK, target framework, and pinned package directives to the source stream and invokes `dotnet run -` for modern .NET targets. If a current-directory project exists, SDK 11 would select it first; csrun instead uses an isolated temporary `.cs` file and `dotnet run --file` to force file-based execution while retaining the program's working directory. It creates no console project for modern .NET targets. Because `dotnet run --file` does not support `.NET Framework` TFMs directly, `.NET Framework` console manifests fall back to an isolated temporary SDK-style `.csproj` (with `LangVersion=latest` and `Microsoft.NETFramework.ReferenceAssemblies`, removed in `finally`) and run via `dotnet run --project ... --framework `. The SDK manages its own normal build cache. Approximate NuGet matches and downgrades are errors, preventing an unavailable pin from silently becoming another version. -Existing source directives must be in the leading preamble (blank lines, leading comments, and C# preprocessor directives such as `#nullable` are permitted). Only matching SDK, target framework, and manifest package directives are supported. Matching directives remain in the original source and are not emitted again. Multiple occurrences of the same source setting fail explicitly because the SDK rejects duplicate directives. Conflicts and other preamble directives also fail explicitly. Build customization outside this contract belongs in a future schema, not arbitrary MSBuild directives. +Existing source directives must be in the leading preamble (blank lines, leading comments, and C# preprocessor directives such as `#nullable` are permitted). Only matching SDK, target framework, and manifest package directives are supported. Matching directives remain in the original source and are not emitted again (and are stripped when falling back to a temporary `.csproj` for `.NET Framework` targets). Multiple occurrences of the same source setting fail explicitly because the SDK rejects duplicate directives. Conflicts and other preamble directives also fail explicitly. Build customization outside this contract belongs in a future schema, not arbitrary MSBuild directives. -Test mode writes the original source to a minimal executable project in a unique temporary directory and runs `dotnet run --project ... -- --show-live-output on --progress off --no-banner`. It uses **xunit.v3@4.0.3** by default, with `UseMicrosoftTestingPlatformRunner=true`. Explicit stable xunit.v3 **4.0 patch versions >= 4.0.3** are accepted as the supported MTP v2 compatibility band; other engine variants and incompatible versions are rejected. User packages are added as exact NuGet references. The project is removed in `finally` after successful runs, compilation/restore errors, or failed tests. Forced process termination cannot guarantee cleanup. +Test mode writes the original source to a minimal executable project in a unique temporary directory and runs `dotnet run --project ... --framework -- --show-live-output on --progress off --no-banner`. It uses **xunit.v3@4.0.3** by default, with `UseMicrosoftTestingPlatformRunner=true`. For `.NET Framework` targets, the project also sets `LangVersion=latest` and references `Microsoft.NETFramework.ReferenceAssemblies` (unless explicitly pinned in `dependsOn`). Explicit stable xunit.v3 **4.0 patch versions >= 4.0.3** are accepted as the supported MTP v2 compatibility band; other engine variants and incompatible versions are rejected. User packages are added as exact NuGet references. The project is removed in `finally` after successful runs, compilation/restore errors, or failed tests. Forced process termination cannot guarantee cleanup. The Codebelt example discovers one passing test and displays `started`, `2`, and `finished` through live `ITestOutputHelper` output. Its `HasTestOutput` assertion only checks that an output helper exists; the integration suite separately verifies the three visible lines. Facts, theories, async tests, constructor injection, fixture disposal, and skipped tests run through the actual xUnit engine. Failed assertions return MTP exit **2**; an empty assembly returns **8**. csrun preserves child stdout/stderr and exit status; validation and prerequisite failures return **1**. `$LASTEXITCODE` is available after local invocation; `pwsh -File ./csrun.ps1 ...` propagates it to the shell. Scriptblock invocation leaves the calling session alive and sets `$LASTEXITCODE`. diff --git a/csrun.ps1 b/csrun.ps1 index 76a0b51..28cfafd 100644 --- a/csrun.ps1 +++ b/csrun.ps1 @@ -6,8 +6,10 @@ Runs a complete trusted C# console program or genuine xUnit v3 tests. .DESCRIPTION Accepts a schemaVersion 1 JSON manifest, or direct options normalized to the same manifest. Requires an installed .NET 10+ SDK and the requested runtime. -The framework defaults to the latest supported GA LTS channel. Explicit targets -are checked against the official release index, cached for up to 12 hours. +The framework defaults to the latest supported GA LTS channel. Explicit +modern .NET targets are checked against the official release index, cached for +up to 12 hours. Legacy .NET Framework targets (net471, net472, net48, net481) +are supported natively on Windows only. Scriptblock callers can inspect $LASTEXITCODE without leaving their session; pwsh -File returns that status to the calling process. Executes code and package build assets with your permissions; this is not a sandbox. @@ -17,7 +19,9 @@ framework, dependsOn, sdk and frameworkReferences fields. Exclusive with direct .PARAMETER Mode console (default) or test. .PARAMETER Framework -Target framework; defaults to the latest supported LTS channel. +Target framework; defaults to the latest supported LTS channel. Accepts .NET 10+ +TFMs (for example net10.0 or net10.0-windows) and Windows-only .NET Framework +TFMs (net471, net472, net48, net481). .PARAMETER DependsOn Explicit PackageId@ExactVersion pins. No floating versions or discovery. .PARAMETER Source @@ -88,14 +92,18 @@ function Get-ReleaseIndex { return ,$index['releases-index'] } -function Resolve-Framework($Framework, $Index) { +function Resolve-Framework($Framework, $Index, [bool] $WindowsPlatform = $IsWindows) { + if ($Framework -is [string] -and $Framework -cmatch '^net4(7[12]|8|81)$') { + if (-not $WindowsPlatform) { throw "Framework '$Framework' targets .NET Framework and is only supported natively on Windows." } + return $Framework + } $channels = @($Index | Where-Object { $_.product -eq '.NET' -and $_['channel-version'] -match '^\d+\.\d+$' -and [version]$_['channel-version'] -ge [version]'10.0' } | Sort-Object { [version]$_['channel-version'] } -Descending) if ($null -eq $Framework) { $lts = @($channels | Where-Object { $_['release-type'] -eq 'lts' -and $_['support-phase'] -in @('active', 'maintenance') -and $_['latest-release'] -match '^\d+\.\d+\.\d+$' }) | Select-Object -First 1 if (-not $lts) { throw 'The release index contains no supported GA LTS channel.' } - return Resolve-Framework "net$($lts['channel-version'])" $Index + return Resolve-Framework "net$($lts['channel-version'])" $Index $WindowsPlatform } - if ($Framework -isnot [string] -or $Framework -cnotmatch '^net(?[1-9][0-9]*\.[0-9]+)(?:-(?:windows|linux|macos|android|ios|maccatalyst|tvos|browser)(?:[0-9]+(?:\.[0-9]+){0,3})?)?$') { throw 'Invalid framework; supply a .NET target framework such as net10.0 or net10.0-windows.' } + if ($Framework -isnot [string] -or $Framework -cnotmatch '^net(?[1-9][0-9]*\.[0-9]+)(?:-(?:windows|linux|macos|android|ios|maccatalyst|tvos|browser)(?:[0-9]+(?:\.[0-9]+){0,3})?)?$') { throw 'Invalid framework; supply a .NET target framework such as net10.0, net10.0-windows, or net48 (Windows only).' } $channel = $Matches.channel $entry = @($channels | Where-Object { $_['channel-version'] -ceq $channel }) if ($entry.Count -ne 1) { throw "Framework '$Framework' has no unique channel in the official .NET release index." } @@ -164,28 +172,55 @@ function Get-ValidatedManifest($InputManifest) { return @{ Mode = $executionMode; Framework = $framework; Source = $InputManifest.source; Sdk = $sdk; Pins = $pins; References = $refs } } -function Get-ConsoleSource($Manifest) { +function Get-ConsoleSource($Manifest, [switch] $StripDirectives) { $directives = [ordered]@{ 'property TargetFramework' = $Manifest.Framework; 'sdk' = $Manifest.Sdk } $seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) foreach ($id in $Manifest.Pins.Keys) { $directives["package $id"] = $Manifest.Pins[$id] } # Inspect only the directive preamble, never C# declarations or method bodies. # Original source is appended byte-for-character, including existing directives. + $source = $Manifest.Source $inBlockComment = $false - foreach ($line in ($Manifest.Source -split '\r\n|\n|\r')) { - $text = $line.Trim() + $removals = [System.Collections.Generic.List[hashtable]]::new() + $pos = 0 + while ($pos -lt $source.Length) { + $eolStart = $source.IndexOfAny([char[]]@("`r", "`n"), $pos) + if ($eolStart -lt 0) { + $lineEnd = $source.Length + $nextPos = $source.Length + } else { + $lineEnd = $eolStart + $nextPos = if ($source[$eolStart] -eq "`r" -and ($eolStart + 1) -lt $source.Length -and $source[$eolStart + 1] -eq "`n") { $eolStart + 2 } else { $eolStart + 1 } + } + $line = $source.Substring($pos, $lineEnd - $pos) + $offset = 0 + $commentEnd = 0 + $hasPrefixComment = $false # Skip leading comments only; do not scan strings or the C# program body. - while ($text.Length -gt 0) { + while ($offset -lt $line.Length) { if ($inBlockComment) { - $end = $text.IndexOf('*/', [StringComparison]::Ordinal) - if ($end -lt 0) { $text = ''; break } - $text = $text.Substring($end + 2).TrimStart(); $inBlockComment = $false - } elseif ($text.StartsWith('/*')) { $inBlockComment = $true; $text = $text.Substring(2) } - else { break } + $end = $line.IndexOf('*/', $offset, [StringComparison]::Ordinal) + if ($end -lt 0) { $offset = $line.Length; break } + $offset = $end + 2 + $commentEnd = $offset + $inBlockComment = $false + $hasPrefixComment = $true + } else { + while ($offset -lt $line.Length -and [char]::IsWhiteSpace($line[$offset])) { $offset++ } + if ($offset -ge $line.Length) { break } + if (($offset + 1) -lt $line.Length -and $line[$offset] -eq '/' -and $line[$offset + 1] -eq '*') { + $inBlockComment = $true + $offset += 2 + $hasPrefixComment = $true + } else { + break + } + } } - if ($text.Length -eq 0 -or $text.StartsWith('//')) { continue } + $text = $line.Substring($offset).TrimEnd() + if ($text.Length -eq 0 -or $text.StartsWith('//')) { $pos = $nextPos; continue } # C# preprocessor directives such as #nullable do not end the SDK's # directive preamble. Leave them untouched, but validate following #: lines. - if ($text.StartsWith('#') -and -not $text.StartsWith('#:')) { continue } + if ($text.StartsWith('#') -and -not $text.StartsWith('#:')) { $pos = $nextPos; continue } if (-not $text.StartsWith('#:')) { break } $key = $null $value = $null @@ -199,6 +234,23 @@ function Get-ConsoleSource($Manifest) { if ($seen.Contains($key)) { throw "Duplicate source directive '$text'; the SDK requires one occurrence per setting." } # A matching directive in the original source supplies this setting. $null = $seen.Add($key) + if ($hasPrefixComment) { + $removals.Add(@{ Start = $pos + $commentEnd; End = $lineEnd }) + } else { + $removals.Add(@{ Start = $pos; End = $nextPos }) + } + $pos = $nextPos + } + if ($StripDirectives) { + if ($removals.Count -eq 0) { return $source } + $builder = [System.Text.StringBuilder]::new($source.Length) + $cursor = 0 + foreach ($span in $removals) { + $null = $builder.Append($source, $cursor, $span.Start - $cursor) + $cursor = $span.End + } + $null = $builder.Append($source, $cursor, $source.Length - $cursor) + return $builder.ToString() } $preamble = foreach ($key in $directives.Keys) { if ($seen.Contains($key)) { continue } @@ -210,7 +262,7 @@ function Get-ConsoleSource($Manifest) { return ($preamble -join "`n") + "`n#:property WarningsAsErrors=NU1603;NU1605`n" + $Manifest.Source } -function Write-TestProject($Manifest, [string] $Directory) { +function Write-Project($Manifest, [string] $Directory, [bool] $IsNetFramework = $false, $SourceOverride = $null) { $project = Join-Path $Directory 'Sample.csproj' $settings = [System.Xml.XmlWriterSettings]::new() $settings.Indent = $true @@ -218,8 +270,11 @@ function Write-TestProject($Manifest, [string] $Directory) { try { $writer.WriteStartElement('Project'); $writer.WriteAttributeString('Sdk', $Manifest.Sdk) $writer.WriteStartElement('PropertyGroup') - foreach ($pair in @{ OutputType = 'Exe'; TargetFramework = $Manifest.Framework; UseMicrosoftTestingPlatformRunner = 'true'; ImplicitUsings = 'enable'; Nullable = 'enable' }.GetEnumerator()) { - $writer.WriteElementString($pair.Key, $pair.Value) + $properties = [ordered]@{ OutputType = 'Exe'; TargetFramework = $Manifest.Framework; ImplicitUsings = 'enable'; Nullable = 'enable'; WarningsAsErrors = 'NU1603;NU1605' } + if ($IsNetFramework) { $properties['LangVersion'] = 'latest' } + if ($Manifest.Mode -eq 'test') { $properties['UseMicrosoftTestingPlatformRunner'] = 'true' } + foreach ($key in $properties.Keys) { + $writer.WriteElementString($key, $properties[$key]) } $writer.WriteEndElement() $writer.WriteStartElement('ItemGroup') @@ -228,13 +283,21 @@ function Write-TestProject($Manifest, [string] $Directory) { # NuGet bracket syntax enforces an exact version rather than a lower bound. $writer.WriteAttributeString('Version', "[$($Manifest.Pins[$id])]"); $writer.WriteEndElement() } + if ($IsNetFramework -and -not $Manifest.Pins.Contains('Microsoft.NETFramework.ReferenceAssemblies')) { + $writer.WriteStartElement('PackageReference') + $writer.WriteAttributeString('Include', 'Microsoft.NETFramework.ReferenceAssemblies') + $writer.WriteAttributeString('Version', '[1.0.3]') + $writer.WriteAttributeString('PrivateAssets', 'All') + $writer.WriteEndElement() + } foreach ($ref in $Manifest.References) { if ($Manifest.Sdk -eq 'Microsoft.NET.Sdk.Web' -and $ref -eq 'Microsoft.AspNetCore.App') { continue } $writer.WriteStartElement('FrameworkReference'); $writer.WriteAttributeString('Include', $ref); $writer.WriteEndElement() } $writer.WriteEndElement(); $writer.WriteEndElement() } finally { $writer.Dispose() } - [System.IO.File]::WriteAllText((Join-Path $Directory 'Sample.cs'), $Manifest.Source, [System.Text.UTF8Encoding]::new($false)) + $sourceText = if ($null -ne $SourceOverride) { $SourceOverride } else { $Manifest.Source } + [System.IO.File]::WriteAllText((Join-Path $Directory 'Sample.cs'), $sourceText, [System.Text.UTF8Encoding]::new($false)) return $project } @@ -258,31 +321,34 @@ try { if ($PSBoundParameters.ContainsKey('Framework')) { $inputManifest.framework = $Framework } } $manifest = Get-ValidatedManifest $inputManifest - $releaseIndex = Get-ReleaseIndex + $isNetFramework = ($manifest.Framework -is [string] -and $manifest.Framework -cmatch '^net4(7[12]|8|81)$') + $releaseIndex = if ($isNetFramework) { $null } else { Get-ReleaseIndex } $manifest.Framework = Resolve-Framework $manifest.Framework $releaseIndex $consoleSource = $null - if ($manifest.Mode -eq 'console') { $consoleSource = Get-ConsoleSource $manifest } + if ($manifest.Mode -eq 'console') { $consoleSource = Get-ConsoleSource $manifest -StripDirectives:$isNetFramework } $dotnet = Get-Command dotnet -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($null -eq $dotnet) { throw 'Missing .NET SDK; install a compatible .NET 10+ SDK and the requested runtime.' } $sdkVersion = & $dotnet.Source --version if ($LASTEXITCODE -ne 0 -or $sdkVersion -notmatch '^(\d+)\.' -or [int]$Matches[1] -lt 10) { throw 'No compatible .NET 10+ SDK selected. Check installed SDKs and the current directory global.json.' } - $null = $manifest.Framework -match '^net(?\d+\.\d+)' - $targetChannel = [version]$Matches.channel - $targetRelease = @($releaseIndex | Where-Object { $_.product -eq '.NET' -and $_['channel-version'] -eq $targetChannel.ToString() })[0] - $selectedVersion = [version](($sdkVersion -split '-')[0]) - if ($selectedVersion.Major -lt $targetChannel.Major -or ($selectedVersion.Major -eq $targetChannel.Major -and $selectedVersion.Minor -lt $targetChannel.Minor)) { throw "Selected SDK $sdkVersion cannot build $($manifest.Framework); select a compatible SDK using global.json or install one." } - $runtimes = @(& $dotnet.Source --list-runtimes) - if ($LASTEXITCODE -ne 0) { throw 'Unable to list installed .NET runtimes.' } - $requiredRuntimes = @('Microsoft.NETCore.App') - if ($manifest.Sdk -eq 'Microsoft.NET.Sdk.Web' -or 'Microsoft.AspNetCore.App' -in $manifest.References) { $requiredRuntimes += 'Microsoft.AspNetCore.App' } - if (@($manifest.References | Where-Object { $_ -match '^Microsoft\.WindowsDesktop\.App(?:\.|$)' }).Count) { $requiredRuntimes += 'Microsoft.WindowsDesktop.App' } - $prereleasePattern = if ($targetRelease['support-phase'] -in @('preview', 'go-live')) { '(?:-[^ ]+)?' } else { '' } - foreach ($runtime in $requiredRuntimes) { - if (-not @($runtimes | Where-Object { $_ -match "^$([regex]::Escape($runtime)) $([regex]::Escape($targetChannel.ToString()))\.\d+$prereleasePattern " }).Count) { throw "Missing $runtime runtime for .NET $targetChannel required by $($manifest.Framework); install the runtime before running csrun." } + if (-not $isNetFramework) { + $null = $manifest.Framework -match '^net(?\d+\.\d+)' + $targetChannel = [version]$Matches.channel + $targetRelease = @($releaseIndex | Where-Object { $_.product -eq '.NET' -and $_['channel-version'] -eq $targetChannel.ToString() })[0] + $selectedVersion = [version](($sdkVersion -split '-')[0]) + if ($selectedVersion.Major -lt $targetChannel.Major -or ($selectedVersion.Major -eq $targetChannel.Major -and $selectedVersion.Minor -lt $targetChannel.Minor)) { throw "Selected SDK $sdkVersion cannot build $($manifest.Framework); select a compatible SDK using global.json or install one." } + $runtimes = @(& $dotnet.Source --list-runtimes) + if ($LASTEXITCODE -ne 0) { throw 'Unable to list installed .NET runtimes.' } + $requiredRuntimes = @('Microsoft.NETCore.App') + if ($manifest.Sdk -eq 'Microsoft.NET.Sdk.Web' -or 'Microsoft.AspNetCore.App' -in $manifest.References) { $requiredRuntimes += 'Microsoft.AspNetCore.App' } + if (@($manifest.References | Where-Object { $_ -match '^Microsoft\.WindowsDesktop\.App(?:\.|$)' }).Count) { $requiredRuntimes += 'Microsoft.WindowsDesktop.App' } + $prereleasePattern = if ($targetRelease['support-phase'] -in @('preview', 'go-live')) { '(?:-[^ ]+)?' } else { '' } + foreach ($runtime in $requiredRuntimes) { + if (-not @($runtimes | Where-Object { $_ -match "^$([regex]::Escape($runtime)) $([regex]::Escape($targetChannel.ToString()))\.\d+$prereleasePattern " }).Count) { throw "Missing $runtime runtime for .NET $targetChannel required by $($manifest.Framework); install the runtime before running csrun." } + } } $dependencies = @($manifest.Pins.Keys | ForEach-Object { "$_@$($manifest.Pins[$_])" }) Write-Host "csrun: $($manifest.Mode) | $($manifest.Framework) | dependencies: $($dependencies -join ', ')" - if ($manifest.Mode -eq 'console') { + if ($manifest.Mode -eq 'console' -and -not $isNetFramework) { $OutputEncoding = [System.Text.UTF8Encoding]::new($false) if (@(Get-ChildItem -LiteralPath (Get-Location).Path -File -Filter '*.*proj').Count -gt 0) { # SDK 11 selects a current-directory project before considering '-'. @@ -296,11 +362,18 @@ try { $consoleSource | & $dotnet.Source run - --no-launch-profile } $exitCode = $LASTEXITCODE + } elseif ($manifest.Mode -eq 'console') { + # File-based apps do not support .NET Framework TFMs directly; fall back to an isolated SDK-style project. + $temporaryDirectory = Join-Path ([System.IO.Path]::GetTempPath()) ('csrun-' + [guid]::NewGuid().ToString('N')) + $null = New-Item -ItemType Directory -Path $temporaryDirectory + $project = Write-Project $manifest $temporaryDirectory $true $consoleSource + & $dotnet.Source run --project $project --framework $manifest.Framework --no-launch-profile + $exitCode = $LASTEXITCODE } else { $temporaryDirectory = Join-Path ([System.IO.Path]::GetTempPath()) ('csrun-' + [guid]::NewGuid().ToString('N')) $null = New-Item -ItemType Directory -Path $temporaryDirectory - $project = Write-TestProject $manifest $temporaryDirectory - & $dotnet.Source run --project $project --no-launch-profile -- --show-live-output on --progress off --no-banner + $project = Write-Project $manifest $temporaryDirectory $isNetFramework + & $dotnet.Source run --project $project --framework $manifest.Framework --no-launch-profile -- --show-live-output on --progress off --no-banner $exitCode = $LASTEXITCODE } } catch { diff --git a/tests/container.Tests.ps1 b/tests/container.Tests.ps1 index 67d56a2..b01ee29 100644 --- a/tests/container.Tests.ps1 +++ b/tests/container.Tests.ps1 @@ -1,4 +1,4 @@ -#requires -Version 7.0 +#requires -Version 7.0 [CmdletBinding()] param( [Parameter(Mandatory)][string] $Image, @@ -198,6 +198,7 @@ Test-Case 'invalid JSON and empty stdin' { } Test-Case 'unsupported framework and conflicting pins fail' { Assert-Result (Invoke-Manifest (New-Manifest 'Console.WriteLine(42);' -Framework net9.0)) 1 'framework|supported' + Assert-Result (Invoke-Manifest (New-Manifest 'Console.WriteLine(42);' -Framework net48)) 1 'only supported natively on Windows' $manifest = New-Manifest 'Console.WriteLine(42);' $manifest.dependsOn = @('Cuemon.Kernel@11.0.0', 'Cuemon.Kernel@11.0.1') Assert-Result (Invoke-Manifest $manifest) 1 'conflict' diff --git a/tests/csrun.Tests.ps1 b/tests/csrun.Tests.ps1 index 75bfdc8..60b675d 100644 --- a/tests/csrun.Tests.ps1 +++ b/tests/csrun.Tests.ps1 @@ -1,4 +1,4 @@ -#requires -Version 7.0 +#requires -Version 7.0 [CmdletBinding()] param( [switch] $CompatibilityOnly, @@ -125,9 +125,15 @@ try { foreach ($tfm in @('net10.0', 'net11.0', 'net11.0-windows10.0.19041.0', 'net13.0')) { if ((Resolve-Framework $tfm $fixture) -cne $tfm) { throw "Changed explicit TFM $tfm" } } - foreach ($tfm in @('net9.0','net12.0','net99.0','win-x64')) { + foreach ($tfm in @('net471', 'net472', 'net48', 'net481')) { + if ((Resolve-Framework $tfm $fixture $true) -cne $tfm) { throw "Changed explicit .NET Framework TFM $tfm" } $rejected = $false - try { $null = Resolve-Framework $tfm $fixture } catch { $rejected = $true } + try { $null = Resolve-Framework $tfm $fixture $false } catch { $rejected = ($_.Exception.Message -match 'only supported natively on Windows') } + if (-not $rejected) { throw "Accepted .NET Framework TFM $tfm on non-Windows" } + } + foreach ($tfm in @('net9.0','net12.0','net99.0','win-x64','netstandard2.0','net45','net46','net461','net462','net47','net482','net48-windows')) { + $rejected = $false + try { $null = Resolve-Framework $tfm $fixture $true } catch { $rejected = $true } if (-not $rejected) { throw "Accepted $tfm" } } $goLive = @($fixture | ForEach-Object { $_.Clone() }) @@ -243,6 +249,85 @@ try { Assert-TestArtifactsRemoved $result } } + Test-Case 'non-Windows runner rejects .NET Framework TFM fail-fast' { + $nonWindowsRunner = Join-Path $root 'non-windows-runner.ps1' + $nonWindowsText = $runnerText.Replace('[bool] $WindowsPlatform = $IsWindows', '[bool] $WindowsPlatform = $false') + if ($nonWindowsText -ceq $runnerText) { throw 'Could not simulate non-Windows platform.' } + [IO.File]::WriteAllText($nonWindowsRunner, $nonWindowsText) + $oldRunner = $script:runner + try { + $script:runner = $nonWindowsRunner + Assert-Result (Invoke-Runner @{Framework='net48'; Source='System.Console.WriteLine(1);'}) 1 'only supported natively on Windows' + } finally { $script:runner = $oldRunner } + } + if ($IsWindows) { + Test-Case 'net48 console resolves lib/netstandard2.0 package asset and preserves exit status' { + $source = @' +using System; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using Cuemon; +var tfm = typeof(DateSpan).Assembly.GetCustomAttribute()?.FrameworkName; +Console.WriteLine("RUNTIME:" + RuntimeInformation.FrameworkDescription); +Console.WriteLine("ASSET_TFM:" + tfm); +Console.WriteLine("DAYS:" + new DateSpan(new DateTime(2018, 1, 1), new DateTime(2018, 10, 1)).TotalDays); +Console.Error.WriteLine("net48 stderr"); +return 23; +'@ + $m = New-Manifest $source console @('Cuemon.Kernel@11.0.0') + $m.framework = 'net48' + $result = Invoke-Manifest $m + Assert-Result $result 23 '(?s)RUNTIME:\.NET Framework.*ASSET_TFM:\.NETStandard,Version=v2\.0.*DAYS:273' + if ($result.Err -notmatch 'net48 stderr') { throw 'Child stderr was lost on net48.' } + if (@(Get-ChildItem -LiteralPath $root -Directory -Filter 'csrun-*').Count) { throw 'Leaked net48 console project artifacts.' } + } + Test-Case 'net48 test mode runs xUnit v3 against lib/netstandard2.0 asset and preserves MTP exit codes' { + $source = @' +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using Cuemon; +using Xunit; +public class Net48Tests { + [Fact] + public void ResolvesNetStandard20AssetOnNetFramework() { + Assert.Contains(".NET Framework", RuntimeInformation.FrameworkDescription); + Assert.Equal(".NETStandard,Version=v2.0", typeof(DateSpan).Assembly.GetCustomAttribute()?.FrameworkName); + } +} +'@ + $m = New-Manifest $source test @('Cuemon.Kernel@11.0.0') + $m.framework = 'net48' + $result = Invoke-Manifest $m + Assert-Result $result 0 '(?s)total: 1.*failed: 0.*succeeded: 1' + Assert-TestArtifactsRemoved $result + $failing = New-Manifest 'using Xunit; public class T { [Fact] public void Fail() { Assert.Equal(1, 2); } }' test + $failing.framework = 'net48' + $failResult = Invoke-Manifest $failing + Assert-Result $failResult 2 'Assert.Equal\(\) Failure' + Assert-TestArtifactsRemoved $failResult + } + Test-Case 'net48 console supports matching preamble directives and rejects conflicts' { + $m = New-Manifest "#:property TargetFramework=net48`n#:sdk Microsoft.NET.Sdk`nSystem.Console.WriteLine(42);" + $m.framework = 'net48' + Assert-Result (Invoke-Manifest $m) 0 '(?m)^42\r?$' + $bad = New-Manifest "#:property TargetFramework=net472`nSystem.Console.WriteLine(42);" + $bad.framework = 'net48' + Assert-Result (Invoke-Manifest $bad) 1 'conflicts' + } + Test-Case 'net48 console preserves closing block comment on directive line' { + $m = New-Manifest "/* header`n*/ #:sdk Microsoft.NET.Sdk`nSystem.Console.WriteLine(42);`n" + $m.framework = 'net48' + Assert-Result (Invoke-Manifest $m) 0 '(?m)^42\r?$' + } + Test-Case 'net48 console preserves CRLF line endings when stripping directives' { + $source = "#:sdk Microsoft.NET.Sdk`r`nvar s = @`"a`r`nb`";`r`nSystem.Console.WriteLine(s.Contains(`"\r\n`"));`r`n" + $m = New-Manifest $source + $m.framework = 'net48' + Assert-Result (Invoke-Manifest $m) 0 '(?m)^True\r?$' + } + } if (-not $CompatibilityOnly) { Test-Case 'inline console and no user project' { $projectsBefore = @(Get-ChildItem $root -Recurse -Filter *.csproj | Select-Object -ExpandProperty FullName | Sort-Object) @@ -426,6 +511,12 @@ public class Tests { @{Name='noninteger schema'; Field='schemaVersion'; Value=1.0; Pattern='schemaVersion'}, @{Name='method mode'; Field='mode'; Value='method'; Pattern='Unsupported mode'}, @{Name='bad TFM'; Field='framework'; Value='win-x64'; Pattern='Invalid framework'}, + @{Name='netstandard2.0 TFM'; Field='framework'; Value='netstandard2.0'; Pattern='Invalid framework'}, + @{Name='unsupported net45 TFM'; Field='framework'; Value='net45'; Pattern='Invalid framework'}, + @{Name='unsupported net462 TFM'; Field='framework'; Value='net462'; Pattern='Invalid framework'}, + @{Name='unsupported net47 TFM'; Field='framework'; Value='net47'; Pattern='Invalid framework'}, + @{Name='unsupported net482 TFM'; Field='framework'; Value='net482'; Pattern='Invalid framework'}, + @{Name='invalid net48-windows TFM'; Field='framework'; Value='net48-windows'; Pattern='Invalid framework'}, @{Name='null framework'; Field='framework'; Value=$null; Pattern='Invalid framework'}, @{Name='empty framework array'; Field='framework'; Value=@(); Pattern='Invalid framework'}, @{Name='single-item framework array'; Field='framework'; Value=@('net10.0'); Pattern='Invalid framework'},