ModernUO/Projects/BuildTool/Prerequisites/DotNetSdkManager.cs
Kamron Batman ec4d6a7a85
feat: Adds Build Tool for Publishing/Setup (#2392)
## Summary

Replaces the basic `publish.cmd`/`publish.sh` scripts with an interactive **BuildTool** — a C# console app using [Spectre.Console](https://spectreconsole.net/) that guides users through publishing, prerequisite checking, and cross-compilation.

### Why
The community found the existing publish scripts unhelpful for newcomers. They worked but didn't walk users through the process, didn't check prerequisites, and provided no feedback when things went wrong.

### What's New

**Interactive BuildTool** (`Projects/BuildTool/`)
- NativeAOT-compiled C# console app with true-color ASCII logo and ModernUO brand gold/silver palette
- Guided publish wizard with step-by-step back navigation (Ctrl+C or menu "Back" to go to previous step)
- Prerequisite checking: .NET SDK version, VC++ Redistributable (Windows), native libraries (Linux/macOS)
- .NET SDK auto-install offer via Microsoft's official install scripts
- Platform detection: Windows 10 vs 11 (build number), macOS codenames, Linux distro + kernel version
- Cross-compilation support: skips native library checks, shows target prerequisites after build
- Non-interactive mode for CI: `--config Release --skip-prereqs`
- Backward-compatible positional args: `publish.cmd release win x64` still works

**Shell Wrappers** (`publish.cmd`, `publish.ps1`, `publish.sh`)
- Try native BuildTool binary first (downloaded from GitHub Releases)
- Fall back to `dotnet run --project Projects/BuildTool` if unavailable
- SDK bootstrapping: offer to install .NET if not found

**CI/CD Updates**
- Build/test workflows target `Projects/Application/Application.csproj` instead of the solution (excludes BuildTool and test projects from publish)
- New `build-tool-release.yml` workflow builds NativeAOT binaries for win-x64, win-arm64, osx-arm64, linux-x64, linux-arm64
- Minimum SDK bumped to 10.0.201 (required for Serialization Generator 2.14.3 / Roslyn 5.3.0)

**Other Changes**
- Solution converted from `.sln` to `.slnx`
- Updated README with interactive mode instructions and deployment guidance

## Screenshots

<img width="320" height="378" alt="image" src="https://github.com/user-attachments/assets/83c057c5-3992-4dbd-99fa-0e3c24ef6428" />

<img width="749" height="554" alt="image" src="https://github.com/user-attachments/assets/e4ee4d6f-71d4-47f9-86b6-8fd1ca3c3e7a" />
2026-03-28 21:21:50 -07:00

190 lines
6.2 KiB
C#

using System.Text.Json;
using System.Text.RegularExpressions;
using BuildTool.Json;
using BuildTool.Platform;
using BuildTool.Publishing;
using Spectre.Console;
namespace BuildTool.Prerequisites;
public static partial class DotNetSdkManager
{
private const string DotNetDownloadUrl = "https://dotnet.microsoft.com/download";
private const string InstallScriptUrlWindows = "https://dot.net/v1/dotnet-install.ps1";
private const string InstallScriptUrlUnix = "https://dot.net/v1/dotnet-install.sh";
public static PrerequisiteResult CheckSdk(string repoRoot)
{
var requiredVersionStr = ReadRequiredVersion(repoRoot) ?? "10.0.201";
if (!Version.TryParse(requiredVersionStr, out var requiredVersion))
{
requiredVersion = new Version(10, 0, 201);
}
// Check if dotnet is on PATH
var result = ProcessRunner.RunCaptured("dotnet", "--list-sdks");
if (!result.Success)
{
return new PrerequisiteResult
{
Name = ".NET SDK",
Passed = false,
Details = $".NET SDK {requiredVersionStr}+ is not installed",
DownloadUrl = DotNetDownloadUrl
};
}
// Parse installed SDK versions — find the best match
Version? bestVersion = null;
string? bestVersionStr = null;
foreach (var line in result.StandardOutput.Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
var match = SdkVersionRegex().Match(line);
if (!match.Success)
{
continue;
}
var versionStr = match.Groups[1].Value;
if (!Version.TryParse(versionStr, out var version))
{
continue;
}
if (bestVersion is null || version > bestVersion)
{
bestVersion = version;
bestVersionStr = versionStr;
}
}
if (bestVersion is null || bestVersion < requiredVersion)
{
return new PrerequisiteResult
{
Name = ".NET SDK",
Passed = false,
Details = bestVersionStr is not null
? $".NET SDK {bestVersionStr} found, but {requiredVersionStr}+ is required"
: $".NET SDK {requiredVersionStr}+ is required but no SDK was found",
DownloadUrl = DotNetDownloadUrl
};
}
return new PrerequisiteResult
{
Name = ".NET SDK",
Passed = true,
Details = $".NET SDK {bestVersionStr}"
};
}
public static bool OfferInstall(PlatformInfo platform, bool interactive)
{
if (!interactive)
{
AnsiConsole.MarkupLine("[red]Error:[/] .NET SDK is not installed. Download from:");
AnsiConsole.MarkupLine($"[link]{DotNetDownloadUrl}[/]");
return false;
}
var install = AnsiConsole.Confirm(
"[yellow].NET SDK is required but not found.[/] Would you like to install it now?",
defaultValue: true
);
if (!install)
{
AnsiConsole.MarkupLine($"\nDownload the .NET SDK from: [link]{DotNetDownloadUrl}[/]");
return false;
}
return RunInstallScript(platform);
}
private static bool RunInstallScript(PlatformInfo platform)
{
AnsiConsole.MarkupLine("\n[blue]Installing .NET SDK...[/]");
if (platform.IsWindows)
{
return RunWindowsInstall();
}
return RunUnixInstall();
}
private static bool RunWindowsInstall()
{
// Download and run the official Microsoft install script
var result = ProcessRunner.RunPassthrough(
"powershell",
$"-NoProfile -ExecutionPolicy Bypass -Command \"& {{ " +
$"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; " +
$"$script = Invoke-WebRequest -Uri '{InstallScriptUrlWindows}' -UseBasicParsing; " +
$"$scriptBlock = [scriptblock]::Create($script.Content); " +
$"& $scriptBlock -Channel 10.0 }}\""
);
if (result != 0)
{
AnsiConsole.MarkupLine("[red]Failed to install .NET SDK.[/]");
AnsiConsole.MarkupLine($"Please install manually from: [link]{DotNetDownloadUrl}[/]");
return false;
}
AnsiConsole.MarkupLine("[green]Successfully installed .NET SDK.[/]");
AnsiConsole.MarkupLine("[yellow]Note:[/] You may need to restart your terminal for the PATH to update.");
return true;
}
private static bool RunUnixInstall()
{
// Download and run the official Microsoft install script
var result = ProcessRunner.RunPassthrough(
"bash",
$"-c \"curl -fsSL {InstallScriptUrlUnix} | bash -s -- --channel 10.0\""
);
if (result != 0)
{
AnsiConsole.MarkupLine("[red]Failed to install .NET SDK.[/]");
AnsiConsole.MarkupLine($"Please install manually from: [link]{DotNetDownloadUrl}[/]");
return false;
}
AnsiConsole.MarkupLine("[green]Successfully installed .NET SDK.[/]");
AnsiConsole.MarkupLine("[yellow]Note:[/] You may need to add ~/.dotnet to your PATH or restart your terminal.");
return true;
}
private static string? ReadRequiredVersion(string repoRoot)
{
var globalJsonPath = Path.Combine(repoRoot, "global.json");
if (!File.Exists(globalJsonPath))
{
return null;
}
var json = File.ReadAllText(globalJsonPath);
var globalJson = JsonSerializer.Deserialize(json, GlobalJsonContext.Default.GlobalJson);
return globalJson?.Sdk?.Version;
}
// Kept for reference but no longer used — Version.TryParse handles comparison now
private static int ParseMajorVersion(string version)
{
var dotIndex = version.IndexOf('.');
if (dotIndex <= 0)
{
return 0;
}
return int.TryParse(version.AsSpan(0, dotIndex), out var major) ? major : 0;
}
[GeneratedRegex(@"^(\d+\.\d+\.\d+\S*)")]
private static partial Regex SdkVersionRegex();
}