Files
Alby96andClaude Opus 5.5 815bd44a62 Prova di costruisci.sh con Git Bash su Windows, mai col lanciatore di WSL
Dal PATH di PowerShell il primo bash è C:\Windows\System32\bash.exe, il lanciatore di WSL: senza
distribuzione fallisce («execvpe(/bin/bash) failed») e la prova falliva con lui. Su Windows ora si
cerca prima Git Bash (accanto a git sul PATH, poi nelle cartelle del suo installatore), poi un bash
sul PATH che non stia nella cartella di Windows né fra gli alias di WindowsApps; senza bash la
prova è inconcludente invece di passare in silenzio. Su Linux si usa come prima il primo bash sul
PATH.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:09:27 +02:00

195 lines
9.7 KiB
C#

using System.Diagnostics;
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Desktop;
/// <summary>
/// The installer of Windows (spec §12, question 6 of §16): <c>installer/febe.nsi</c> compiles with makensis (a dry
/// compile with a stand-in Febe.exe; skipped where NSIS is not installed), installs per user without administrator
/// rights, registers its uninstaller in HKCU, and its uninstaller never deletes the Data folder or the library.
/// </summary>
[TestClass]
public sealed partial class InstallerTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheScriptCompilesWithMakensisWithoutWarnings()
{
var makensis = FindOnPath("makensis");
if (makensis is null)
{
Assert.Inconclusive("makensis non è installato (apt-get install nsis): la prova del programma di installazione si salta.");
}
var script = Repository.PathOf("installer", "febe.nsi");
using var temp = new TempFolder("nsis");
await File.WriteAllTextAsync(temp.Combine("Febe.exe"), "MZ finto per la prova", TestContext.CancellationToken);
var output = temp.Combine("Febe-Setup-0.0.1.exe");
var start = new ProcessStartInfo(makensis)
{
WorkingDirectory = Path.GetDirectoryName(script)!,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (var argument in new[] { "-V2", "-WX", "-INPUTCHARSET", "UTF8", "-DVERSION=0.0.1", "-DVERSIONE_FILE=0.0.1.0", $"-DSORGENTE={temp.Path}", $"-DUSCITA={output}", "febe.nsi" })
{
start.ArgumentList.Add(argument);
}
using var process = Process.Start(start)!;
var stdout = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
var stderr = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
await process.WaitForExitAsync(TestContext.CancellationToken);
Assert.AreEqual(0, process.ExitCode, $"makensis (avvisi = errori):\n{await stdout}\n{await stderr}");
Assert.IsTrue(File.Exists(output));
Assert.IsGreaterThan(100_000L, new FileInfo(output).Length);
// Without the version the script refuses to compile: it always comes from the build.
using var noVersion = Process.Start(new ProcessStartInfo(makensis, ["-V1", $"-DSORGENTE={temp.Path}", $"-DUSCITA={temp.Combine("x.exe")}", "febe.nsi"])
{
WorkingDirectory = Path.GetDirectoryName(script)!,
RedirectStandardOutput = true,
RedirectStandardError = true,
})!;
await noVersion.WaitForExitAsync(TestContext.CancellationToken);
Assert.AreNotEqual(0, noVersion.ExitCode);
}
[TestMethod]
public void TheScriptInstallsPerUserAndItsUninstallerNeverTouchesTheData()
{
var text = File.ReadAllText(Repository.PathOf("installer", "febe.nsi"));
StringAssert.Contains(text, "Unicode true");
StringAssert.Contains(text, "RequestExecutionLevel user");
StringAssert.Contains(text, "InstallDir \"$LOCALAPPDATA\\Programs\\Febe\"");
StringAssert.Contains(text, "MUI_LANGUAGE \"Italian\"");
StringAssert.Contains(text, "$SMPROGRAMS\\Febe.lnk");
StringAssert.Contains(text, "Section \"Collegamento sul desktop\"");
foreach (var value in new[] { "DisplayName", "DisplayVersion", "Publisher", "DisplayIcon", "UninstallString" })
{
StringAssert.Contains(text, $"WriteRegStr HKCU \"${{CHIAVE_DISINSTALLA}}\" \"{value}\"");
}
StringAssert.Contains(text, "\"DisplayVersion\" \"${VERSION}\"");
StringAssert.Contains(text, "\"Publisher\" \"${EDITORE}\"");
StringAssert.Contains(text, "!define EDITORE \"Alberto Balbo\"");
StringAssert.Contains(text, "EdgeUpdate\\Clients\\${WEBVIEW2_GUID}");
StringAssert.Contains(text, "https://developer.microsoft.com/microsoft-edge/webview2/");
Assert.DoesNotContain("HKLM\" \"${CHIAVE", text, "nothing written for every user");
Assert.IsFalse(Regex.IsMatch(text, @"Write\w*\s+HKLM"), "no machine-wide registry");
// The uninstall section deletes only the program, its shortcuts and its registry entries.
var uninstall = text[text.IndexOf("Section \"Uninstall\"", StringComparison.Ordinal)..];
uninstall = uninstall[..uninstall.IndexOf("SectionEnd", StringComparison.Ordinal)];
foreach (Match removal in Removals().Matches(uninstall))
{
var target = removal.Groups["target"].Value;
Assert.IsTrue(
target.StartsWith("$INSTDIR\\", StringComparison.Ordinal) || target == "$INSTDIR"
|| target is "$SMPROGRAMS\\Febe.lnk" or "$DESKTOP\\Febe.lnk" or "$TEMP\\.net\\Febe",
$"the uninstaller removes «{target}»: only the program may go");
}
Assert.DoesNotContain("$LOCALAPPDATA\\Febe", uninstall.Replace("StrCpy $R8 \"$LOCALAPPDATA\\Febe\"", string.Empty, StringComparison.Ordinal), "never the Data folder");
Assert.DoesNotContain("$PICTURES", uninstall, "never the library");
Assert.DoesNotContain("MB_YESNO", uninstall, "it asks nothing about the data");
StringAssert.Contains(uninstall, "DeleteRegValue HKCU \"${CHIAVE_AVVIO}\" \"Febe\"", "the start with the computer goes with the program");
}
[TestMethod]
public void TheBuildScriptIsValidBashAndProducesTheTwoFilesUnder100Mb()
{
var script = Repository.PathOf("installer", "costruisci.sh");
var text = File.ReadAllText(script);
StringAssert.Contains(text, "set -euo pipefail");
StringAssert.Contains(text, "-p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true");
StringAssert.Contains(text, "Febe-Setup-$versione.exe");
StringAssert.Contains(text, "Febe-$versione-portabile.zip");
StringAssert.Contains(text, "100 * 1024 * 1024");
Assert.DoesNotContain("\r\n", text, "Unix line ends: bash would choke on CR");
var bash = FindBash();
if (bash is null)
{
Assert.Inconclusive("Manca bash (su Windows: Git Bash): la prova della sintassi di costruisci.sh si salta.");
}
using var process = Process.Start(new ProcessStartInfo(bash, ["-n", script]) { RedirectStandardError = true })!;
var errors = process.StandardError.ReadToEnd();
process.WaitForExit();
Assert.AreEqual(0, process.ExitCode, errors);
}
private static string? FindOnPath(string name) => OnPath(name).FirstOrDefault();
/// <summary>
/// A bash that checks the script on this system. Elsewhere than Windows, the first on PATH. On Windows Git Bash
/// first (next to git on PATH, then where its installer puts it), else any bash on PATH except the WSL launcher:
/// <c>System32\bash.exe</c> and the <c>WindowsApps</c> alias start a Linux distribution, which may be missing
/// («execvpe(/bin/bash) failed») and does not see the script by its Windows path.
/// </summary>
private static string? FindBash()
{
if (!OperatingSystem.IsWindows())
{
return FindOnPath("bash");
}
var roots = new List<string>();
if (FindOnPath("git") is { } git)
{
// git.exe sits in <Git>\cmd, <Git>\bin or <Git>\mingw64\bin.
for (var folder = Path.GetDirectoryName(git); folder is not null && roots.Count < 3; folder = Path.GetDirectoryName(folder))
{
roots.Add(folder);
}
}
foreach (var variable in new[] { "ProgramW6432", "ProgramFiles", "ProgramFiles(x86)" })
{
if (Environment.GetEnvironmentVariable(variable) is { Length: > 0 } programs)
{
roots.Add(Path.Combine(programs, "Git"));
}
}
roots.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Git"));
var gitBash = roots
.SelectMany(root => new[] { Path.Combine(root, "bin", "bash.exe"), Path.Combine(root, "usr", "bin", "bash.exe") })
.FirstOrDefault(path => File.Exists(path) && !IsWslLauncher(path));
return gitBash ?? OnPath("bash").FirstOrDefault(path => !IsWslLauncher(path));
}
private static bool IsWslLauncher(string path)
{
var full = Path.GetFullPath(path);
var windows = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
return (windows.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(windows) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|| full.Contains(@"\Microsoft\WindowsApps\", StringComparison.OrdinalIgnoreCase);
}
/// <summary>Every file called <paramref name="name"/> on PATH, in order (on Windows only <c>.exe</c>: the others do not start).</summary>
private static IEnumerable<string> OnPath(string name)
{
var candidates = OperatingSystem.IsWindows() ? new[] { name + ".exe" } : new[] { name, name + ".exe" };
foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
foreach (var candidate in candidates)
{
var path = Path.Combine(folder, candidate);
if (File.Exists(path))
{
yield return path;
}
}
}
}
[GeneratedRegex(@"^\s*(?:Delete|RMDir)(?:\s+/\w+)*\s+""(?<target>[^""]+)""", RegexOptions.Multiline)]
private static partial Regex Removals();
}