From 7d3910b1525a28b07f608f4a4a5b4f5c95ed125a Mon Sep 17 00:00:00 2001 From: Daniel Fischer Date: Fri, 13 Nov 2026 21:39:20 +0100 Subject: [PATCH] feat(app): add `rta update` to install the latest GitHub release Checks the latest release on GitHub and installs it when it is newer than the running version (`--check` only reports). The single-file zip is verified against SHA256SUMS.txt and unpacked over the program folder (the running exe is renamed to *.old and removed on the next run); a dotnet tool install is updated from the release's nupkg via `dotnet tool update -g`. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 5 +- raidTimeline.App.Tests/UpdateServiceTests.cs | 195 +++++++++++ raidTimeline.App/Commands/UpdateCommands.cs | 124 +++++++ raidTimeline.App/Program.cs | 1 + raidTimeline.App/Services/UpdateService.cs | 329 +++++++++++++++++++ 5 files changed, 652 insertions(+), 2 deletions(-) create mode 100644 raidTimeline.App.Tests/UpdateServiceTests.cs create mode 100644 raidTimeline.App/Commands/UpdateCommands.cs create mode 100644 raidTimeline.App/Services/UpdateService.cs diff --git a/README.md b/README.md index 11aac60..d3f4cec 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Commands: clean Commands to clean log file folders and free up space. size Commands to show the disk space taken by logs. upload Commands for uploading html and log files. + update Installs the latest release from GitHub if it is newer than this version. ``` ### Features @@ -44,7 +45,7 @@ Commands: dotnet tool install -g rta ``` -Update with `dotnet tool update -g rta`. The tool is also attached to every +Update with `rta update` (or `dotnet tool update -g rta`). The tool is also attached to every [release](https://github.com/danifischer/raidTimeline/releases/latest) as `rta..nupkg`; install that file with `dotnet tool install -g rta --add-source --version `. @@ -53,7 +54,7 @@ Update with `dotnet tool update -g rta`. The tool is also attached to every 1. Download `rta-v-win-x64.zip` from the [latest release](https://github.com/danifischer/raidTimeline/releases/latest) (`SHA256SUMS.txt` lets you verify the download) 2. Unpack the zip file and run `rta.exe` via command line (you can put the folder in your `PATH` variable for easy access) -3. To update, replace the files with the ones of the new zip; your settings stay (see Configuration) +3. To update, run `rta update` (it downloads the new zip, checks it against `SHA256SUMS.txt` and replaces the files); your settings stay (see Configuration) Then run `rta config edit` and enter the options you need (see Configuration). diff --git a/raidTimeline.App.Tests/UpdateServiceTests.cs b/raidTimeline.App.Tests/UpdateServiceTests.cs new file mode 100644 index 0000000..3973af4 --- /dev/null +++ b/raidTimeline.App.Tests/UpdateServiceTests.cs @@ -0,0 +1,195 @@ +using System.IO.Compression; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using raidTimeline.App.Services; +using Xunit; + +namespace raidTimeline.App.Tests; + +public sealed class UpdateServiceTests : IDisposable +{ + private readonly string _folder = Path.Combine(Path.GetTempPath(), "rta-update-tests-" + Guid.NewGuid().ToString("N")); + + public UpdateServiceTests() + { + Directory.CreateDirectory(_folder); + } + + public void Dispose() + { + if (Directory.Exists(_folder)) Directory.Delete(_folder, true); + } + + private sealed class StubHandler : HttpMessageHandler + { + private readonly Func _respond; + + public StubHandler(Func respond) => _respond = respond; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) => + Task.FromResult(_respond(request.RequestUri!)); + } + + private static SemVer V(string text) + { + Assert.True(SemVer.TryParse(text, out var version)); + return version; + } + + [Theory] + [InlineData("3.1.0", "3.0.0", 1)] + [InlineData("v3.0.1", "3.0.0", 1)] + [InlineData("3.0.0", "3.0.0+abc123", 0)] + [InlineData("3.0.0", "3.0.0-beta.1", 1)] + [InlineData("3.0.0-beta.2", "3.0.0-beta.10", -1)] + [InlineData("3.0.0-alpha", "3.0.0-beta", -1)] + [InlineData("3.0.0-1", "3.0.0-alpha", -1)] + [InlineData("3.0.0-beta", "3.0.0-beta.1", -1)] + [InlineData("2.9.9", "3.0.0", -1)] + public void SemVer_Compares(string left, string right, int expected) + { + Assert.Equal(expected, Math.Sign(V(left).CompareTo(V(right)))); + } + + [Theory] + [InlineData("")] + [InlineData("latest")] + [InlineData("3.0")] + public void SemVer_RejectsNonVersions(string text) + { + Assert.False(SemVer.TryParse(text, out _)); + } + + [Fact] + public async Task GetLatestReleaseAsync_ReadsTagAndAssets() + { + var service = new UpdateService(new HttpClient(new StubHandler(_ => Json(""" + { "tag_name": "v3.1.0", "assets": [ + { "name": "SHA256SUMS.txt", "browser_download_url": "https://example.test/sums" }, + { "name": "rta.3.1.0.nupkg", "browser_download_url": "https://example.test/rta" } ] } + """)))); + + var release = await service.GetLatestReleaseAsync(CancellationToken.None); + + Assert.Equal("3.1.0", release.Version.ToString()); + Assert.Equal("https://example.test/rta", release.Find("RTA.3.1.0.nupkg")?.Url); + } + + [Fact] + public async Task GetLatestReleaseAsync_HttpError_Throws() + { + var service = new UpdateService(new HttpClient(new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.Forbidden)))); + + await Assert.ThrowsAsync(() => service.GetLatestReleaseAsync(CancellationToken.None)); + } + + [Fact] + public async Task GetLatestReleaseAsync_NotARelease_Throws() + { + var service = new UpdateService(new HttpClient(new StubHandler(_ => Json("""{ "message": "Not Found" }""")))); + + await Assert.ThrowsAsync(() => service.GetLatestReleaseAsync(CancellationToken.None)); + } + + [Fact] + public async Task DownloadVerifiedAsync_MatchingChecksum_ReturnsFile() + { + var content = Encoding.UTF8.GetBytes("zip content"); + var release = Release(); + var service = ServiceFor(content, Hash(content) + " rta-v3.1.0-win-x64.zip\n"); + + var path = await service.DownloadVerifiedAsync(release, "rta-v3.1.0-win-x64.zip", _folder, CancellationToken.None); + + Assert.Equal(content, await File.ReadAllBytesAsync(path)); + } + + [Fact] + public async Task DownloadVerifiedAsync_WrongChecksum_Throws() + { + var service = ServiceFor(new byte[] { 1, 2, 3 }, new string('0', 64) + " rta-v3.1.0-win-x64.zip\n"); + + await Assert.ThrowsAsync(() => + service.DownloadVerifiedAsync(Release(), "rta-v3.1.0-win-x64.zip", _folder, CancellationToken.None)); + } + + [Fact] + public async Task DownloadVerifiedAsync_NoEntryInChecksums_Throws() + { + var service = ServiceFor(new byte[] { 1 }, new string('0', 64) + " something-else.zip\n"); + + await Assert.ThrowsAsync(() => + service.DownloadVerifiedAsync(Release(), "rta-v3.1.0-win-x64.zip", _folder, CancellationToken.None)); + } + + [Fact] + public void InstallZip_ReplacesFilesAndKeepsTheOldOnesUntilCleanup() + { + var target = Path.Combine(_folder, "app"); + Directory.CreateDirectory(target); + File.WriteAllText(Path.Combine(target, "rta.exe"), "old exe"); + var zip = CreateZip(("rta.exe", "new exe"), ("config.json", "{}")); + + UpdateService.InstallZip(zip, target); + + Assert.Equal("new exe", File.ReadAllText(Path.Combine(target, "rta.exe"))); + Assert.Equal("{}", File.ReadAllText(Path.Combine(target, "config.json"))); + Assert.Equal("old exe", File.ReadAllText(Path.Combine(target, "rta.exe.old"))); + + UpdateService.DeleteOldFiles(target); + + Assert.False(File.Exists(Path.Combine(target, "rta.exe.old"))); + } + + [Fact] + public void InstallZip_FileOutsideOfTheFolder_Throws() + { + var target = Path.Combine(_folder, "app"); + Directory.CreateDirectory(target); + var zip = CreateZip(("rta.exe", "new exe"), ("../evil.txt", "x")); + + Assert.Throws(() => UpdateService.InstallZip(zip, target)); + Assert.False(File.Exists(Path.Combine(target, "rta.exe"))); + Assert.False(File.Exists(Path.Combine(_folder, "evil.txt"))); + } + + [Fact] + public void InstallZip_WithoutExe_Throws() + { + var target = Path.Combine(_folder, "app"); + Directory.CreateDirectory(target); + + Assert.Throws(() => UpdateService.InstallZip(CreateZip(("readme.txt", "x")), target)); + } + + private static HttpResponseMessage Json(string json) => + new(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + + private static string Hash(byte[] content) => Convert.ToHexString(SHA256.HashData(content)).ToLowerInvariant(); + + private static ReleaseInfo Release() => new("v3.1.0", V("3.1.0"), new[] + { + new ReleaseAsset("rta-v3.1.0-win-x64.zip", "https://example.test/zip"), + new ReleaseAsset("SHA256SUMS.txt", "https://example.test/sums") + }); + + private static UpdateService ServiceFor(byte[] zip, string sums) => + new(new HttpClient(new StubHandler(uri => uri.AbsolutePath == "/sums" + ? new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(sums) } + : new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(zip) }))); + + private string CreateZip(params (string Name, string Content)[] files) + { + var path = Path.Combine(_folder, Guid.NewGuid().ToString("N") + ".zip"); + using var stream = File.Create(path); + using var archive = new ZipArchive(stream, ZipArchiveMode.Create); + foreach (var (name, content) in files) + { + var entry = archive.CreateEntry(name); + using var writer = new StreamWriter(entry.Open()); + writer.Write(content); + } + + return path; + } +} diff --git a/raidTimeline.App/Commands/UpdateCommands.cs b/raidTimeline.App/Commands/UpdateCommands.cs new file mode 100644 index 0000000..3e3e8c9 --- /dev/null +++ b/raidTimeline.App/Commands/UpdateCommands.cs @@ -0,0 +1,124 @@ +using Cocona; +using CliWrap; +using raidTimeline.App.Services; + +namespace raidTimeline.App.Commands; + +internal static class UpdateCommands +{ + internal static CoconaApp RegisterUpdateCommands(this CoconaApp app) + { + app.AddCommand("update", async ( + [Option('c', Description = "Only checks if there is a newer release, installs nothing.")] + bool check, + CoconaAppContext context) => + { + using var httpClient = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }; + return await RunAsync(new UpdateService(httpClient), check, AppContext.BaseDirectory, + context.CancellationToken); + }) + .WithDescription("Installs the latest release from GitHub if it is newer than this version."); + + return app; + } + + private static async Task RunAsync(UpdateService service, bool checkOnly, string baseDirectory, + CancellationToken cancellationToken) + { + UpdateService.DeleteOldFiles(baseDirectory); + + var current = UpdateService.CurrentVersion; + ReleaseInfo release; + try + { + release = await service.GetLatestReleaseAsync(cancellationToken); + } + catch (UpdateException e) + { + Console.Error.WriteLine(e.Message); + return 1; + } + + if (release.Version.CompareTo(current) <= 0) + { + Console.WriteLine($"rta {current} is up to date (latest release: {release.Version})."); + return 0; + } + + Console.WriteLine($"New release {release.Version} available (you have {current})."); + if (checkOnly) + { + Console.WriteLine("Run \"rta update\" to install it."); + return 0; + } + + var folder = Path.Combine(Path.GetTempPath(), "rta-update-" + Guid.NewGuid().ToString("N")); + try + { + if (UpdateService.IsDotnetTool(baseDirectory)) + { + return await UpdateToolAsync(service, release, folder, cancellationToken); + } + + if (!OperatingSystem.IsWindows()) + { + Console.Error.WriteLine( + $"The single file release is only built for Windows. Download {release.Tag} from https://github.com/{UpdateService.Repository}/releases/latest"); + return 1; + } + + var zip = await service.DownloadVerifiedAsync(release, UpdateService.ZipName(release.Version), folder, + cancellationToken); + UpdateService.InstallZip(zip, baseDirectory); + Console.WriteLine($"Updated to {release.Version}. Your settings were not touched."); + return 0; + } + catch (UpdateException e) + { + Console.Error.WriteLine(e.Message); + return 1; + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidDataException) + { + Console.Error.WriteLine($"The update failed: {e.Message}"); + return 1; + } + finally + { + try + { + if (Directory.Exists(folder)) Directory.Delete(folder, true); + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + } + } + } + + private static async Task UpdateToolAsync(UpdateService service, ReleaseInfo release, string folder, + CancellationToken cancellationToken) + { + await service.DownloadVerifiedAsync(release, UpdateService.NupkgName(release.Version), folder, cancellationToken); + + var arguments = new[] + { + "tool", "update", "-g", "rta", "--add-source", folder, "--version", release.Version.ToString() + }; + Console.WriteLine($"dotnet {string.Join(' ', arguments)}"); + + var result = await Cli.Wrap("dotnet") + .WithArguments(arguments) + .WithStandardOutputPipe(PipeTarget.ToStream(Console.OpenStandardOutput())) + .WithStandardErrorPipe(PipeTarget.ToStream(Console.OpenStandardError())) + .WithValidation(CommandResultValidation.None) + .ExecuteAsync(cancellationToken); + + if (result.ExitCode != 0) + { + Console.Error.WriteLine( + $"dotnet tool update failed ({result.ExitCode}). Run \"dotnet tool update -g rta\" yourself."); + } + + return result.ExitCode; + } +} diff --git a/raidTimeline.App/Program.cs b/raidTimeline.App/Program.cs index 70d3f63..654c30f 100644 --- a/raidTimeline.App/Program.cs +++ b/raidTimeline.App/Program.cs @@ -58,5 +58,6 @@ app.RegisterFileCommands(); app.RegisterUploadCommands(); app.RegisterDatabaseCommands(); +app.RegisterUpdateCommands(); app.Run(); \ No newline at end of file diff --git a/raidTimeline.App/Services/UpdateService.cs b/raidTimeline.App/Services/UpdateService.cs new file mode 100644 index 0000000..faa8c1b --- /dev/null +++ b/raidTimeline.App/Services/UpdateService.cs @@ -0,0 +1,329 @@ +using System.IO.Compression; +using System.Reflection; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace raidTimeline.App.Services; + +internal sealed class UpdateException : Exception +{ + public UpdateException(string message) : base(message) + { + } +} + +/// A version like 3.1.0 or 3.1.0-beta.1 (build metadata after a + is ignored). +internal sealed partial class SemVer : IComparable +{ + private readonly string[] _preRelease; + + private SemVer(int major, int minor, int patch, string[] preRelease) + { + Major = major; + Minor = minor; + Patch = patch; + _preRelease = preRelease; + } + + public static SemVer Zero { get; } = new(0, 0, 0, Array.Empty()); + + public int Major { get; } + public int Minor { get; } + public int Patch { get; } + + public static bool TryParse(string? text, out SemVer version) + { + version = null!; + if (text == null) return false; + + var match = VersionPattern().Match(text.Trim()); + if (!match.Success) return false; + + var preRelease = match.Groups["pre"].Success + ? match.Groups["pre"].Value.Split('.') + : Array.Empty(); + version = new SemVer(int.Parse(match.Groups["major"].Value), int.Parse(match.Groups["minor"].Value), + int.Parse(match.Groups["patch"].Value), preRelease); + return true; + } + + public int CompareTo(SemVer? other) + { + if (other == null) return 1; + + var result = Major.CompareTo(other.Major); + if (result != 0) return result; + result = Minor.CompareTo(other.Minor); + if (result != 0) return result; + result = Patch.CompareTo(other.Patch); + if (result != 0) return result; + + // 3.1.0-beta.1 comes before 3.1.0 + if (_preRelease.Length == 0 || other._preRelease.Length == 0) + { + return other._preRelease.Length.CompareTo(_preRelease.Length); + } + + for (var i = 0; i < Math.Min(_preRelease.Length, other._preRelease.Length); i++) + { + var left = _preRelease[i]; + var right = other._preRelease[i]; + var leftIsNumber = int.TryParse(left, out var leftNumber); + var rightIsNumber = int.TryParse(right, out var rightNumber); + + result = (leftIsNumber, rightIsNumber) switch + { + (true, true) => leftNumber.CompareTo(rightNumber), + (true, false) => -1, // numbers come before text + (false, true) => 1, + _ => string.CompareOrdinal(left, right) + }; + if (result != 0) return result; + } + + return _preRelease.Length.CompareTo(other._preRelease.Length); + } + + public override string ToString() => + $"{Major}.{Minor}.{Patch}" + (_preRelease.Length > 0 ? "-" + string.Join('.', _preRelease) : ""); + + [GeneratedRegex(@"^v?(?\d+)\.(?\d+)\.(?\d+)(-(?
[0-9A-Za-z.-]+))?(\+.*)?$")]
+    private static partial Regex VersionPattern();
+}
+
+internal sealed record ReleaseAsset(string Name, string Url);
+
+internal sealed record ReleaseInfo(string Tag, SemVer Version, IReadOnlyList Assets)
+{
+    public ReleaseAsset? Find(string name) =>
+        Assets.FirstOrDefault(a => string.Equals(a.Name, name, StringComparison.OrdinalIgnoreCase));
+}
+
+/// Looks for a newer release on GitHub and installs it.
+internal sealed class UpdateService
+{
+    internal const string Repository = "danifischer/raidTimeline";
+    internal const string OldFileSuffix = ".old";
+
+    private readonly HttpClient _httpClient;
+    private readonly string _latestReleaseUrl;
+
+    public UpdateService(HttpClient httpClient, string latestReleaseUrl =
+        $"https://api.github.com/repos/{Repository}/releases/latest")
+    {
+        _httpClient = httpClient;
+        _latestReleaseUrl = latestReleaseUrl;
+    }
+
+    /// The version of the running program.
+    public static SemVer CurrentVersion
+    {
+        get
+        {
+            var assembly = typeof(UpdateService).Assembly;
+            var text = assembly.GetCustomAttribute()?.InformationalVersion
+                       ?? assembly.GetName().Version?.ToString(3);
+            SemVer.TryParse(text, out var version);
+            return version ?? SemVer.Zero;
+        }
+    }
+
+    /// 
+    /// rta was installed with "dotnet tool install" (the program is a dll started by a shim) and not unpacked from
+    /// the zip file of a release (a single file).
+    /// 
+    public static bool IsDotnetTool(string baseDirectory) =>
+        File.Exists(Path.Combine(baseDirectory, "rta.dll"));
+
+    public static string ZipName(SemVer version) => $"rta-v{version}-win-x64.zip";
+
+    public static string NupkgName(SemVer version) => $"rta.{version}.nupkg";
+
+    /// GitHub did not answer with a usable release.
+    public async Task GetLatestReleaseAsync(CancellationToken cancellationToken)
+    {
+        using var request = new HttpRequestMessage(HttpMethod.Get, _latestReleaseUrl);
+        request.Headers.UserAgent.ParseAdd("rta-update");
+        request.Headers.Accept.ParseAdd("application/vnd.github+json");
+
+        string body;
+        try
+        {
+            using var response = await _httpClient.SendAsync(request, cancellationToken);
+            if (!response.IsSuccessStatusCode)
+            {
+                throw new UpdateException(
+                    $"GitHub answered with {(int)response.StatusCode} {response.ReasonPhrase} when asking for the latest release.");
+            }
+
+            body = await response.Content.ReadAsStringAsync(cancellationToken);
+        }
+        catch (HttpRequestException e)
+        {
+            throw new UpdateException($"GitHub could not be reached: {e.Message}");
+        }
+
+        try
+        {
+            using var document = JsonDocument.Parse(body);
+            var root = document.RootElement;
+            var tag = root.GetProperty("tag_name").GetString();
+            if (!SemVer.TryParse(tag, out var version))
+            {
+                throw new UpdateException($"The latest release has the tag '{tag}', which is not a version.");
+            }
+
+            var assets = new List();
+            foreach (var asset in root.GetProperty("assets").EnumerateArray())
+            {
+                var name = asset.GetProperty("name").GetString();
+                var url = asset.GetProperty("browser_download_url").GetString();
+                if (name != null && url != null) assets.Add(new ReleaseAsset(name, url));
+            }
+
+            return new ReleaseInfo(tag!, version, assets);
+        }
+        catch (Exception e) when (e is JsonException or KeyNotFoundException or InvalidOperationException)
+        {
+            throw new UpdateException("GitHub answered with something that is not a release.");
+        }
+    }
+
+    /// Downloads the asset and checks it against the SHA256SUMS.txt of the release.
+    /// The files are missing, could not be downloaded or the checksum differs.
+    public async Task DownloadVerifiedAsync(ReleaseInfo release, string assetName, string folder,
+        CancellationToken cancellationToken)
+    {
+        var asset = release.Find(assetName)
+                    ?? throw new UpdateException($"The release {release.Tag} has no file {assetName}.");
+        var sums = release.Find("SHA256SUMS.txt")
+                   ?? throw new UpdateException(
+                       $"The release {release.Tag} has no SHA256SUMS.txt, the download cannot be verified.");
+
+        Directory.CreateDirectory(folder);
+        var path = Path.Combine(folder, assetName);
+
+        try
+        {
+            var sumsText = await _httpClient.GetStringAsync(sums.Url, cancellationToken);
+            await using (var stream = await _httpClient.GetStreamAsync(asset.Url, cancellationToken))
+            await using (var file = new FileStream(path, FileMode.Create, FileAccess.Write))
+            {
+                await stream.CopyToAsync(file, cancellationToken);
+            }
+
+            VerifyChecksum(path, sumsText);
+        }
+        catch (HttpRequestException e)
+        {
+            throw new UpdateException($"{assetName} could not be downloaded: {e.Message}");
+        }
+
+        return path;
+    }
+
+    internal static void VerifyChecksum(string path, string sumsText)
+    {
+        var name = Path.GetFileName(path);
+        var expected = sumsText
+            .Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+            .Select(line => line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+            .Where(parts => parts.Length == 2 && string.Equals(parts[1].TrimStart('*'), name,
+                StringComparison.OrdinalIgnoreCase))
+            .Select(parts => parts[0])
+            .FirstOrDefault()
+            ?? throw new UpdateException($"SHA256SUMS.txt has no entry for {name}.");
+
+        using var file = File.OpenRead(path);
+        var actual = Convert.ToHexString(SHA256.HashData(file));
+        if (!string.Equals(expected, actual, StringComparison.OrdinalIgnoreCase))
+        {
+            throw new UpdateException($"The checksum of {name} does not match SHA256SUMS.txt, nothing was installed.");
+        }
+    }
+
+    /// 
+    /// Unpacks the zip into the folder of the program. A running exe cannot be overwritten, but it can be renamed:
+    /// replaced files are kept as *.old until  removes them on the next run.
+    /// 
+    public static void InstallZip(string zipPath, string targetDirectory)
+    {
+        var root = Path.GetFullPath(targetDirectory) + Path.DirectorySeparatorChar;
+
+        using var archive = ZipFile.OpenRead(zipPath);
+
+        // check everything before touching a file
+        var entries = new List<(ZipArchiveEntry Entry, string Target)>();
+        foreach (var entry in archive.Entries.Where(e => !string.IsNullOrEmpty(e.Name)))
+        {
+            var target = Path.GetFullPath(Path.Combine(targetDirectory, entry.FullName));
+            if (!target.StartsWith(root, StringComparison.OrdinalIgnoreCase))
+            {
+                throw new UpdateException($"The zip contains a file outside of the folder ({entry.FullName}).");
+            }
+
+            entries.Add((entry, target));
+        }
+
+        if (!entries.Any(e => e.Target.EndsWith("rta.exe", StringComparison.OrdinalIgnoreCase)))
+        {
+            throw new UpdateException("The zip does not contain rta.exe.");
+        }
+
+        var replaced = new List<(string Old, string Target)>();
+        try
+        {
+            foreach (var (entry, target) in entries)
+            {
+                Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+                if (File.Exists(target))
+                {
+                    var old = target + OldFileSuffix;
+                    File.Move(target, old, true);
+                    replaced.Add((old, target));
+                }
+
+                entry.ExtractToFile(target, true);
+            }
+        }
+        catch
+        {
+            // put the old version back
+            foreach (var (old, target) in replaced)
+            {
+                try
+                {
+                    File.Move(old, target, true);
+                }
+                catch (IOException)
+                {
+                }
+            }
+
+            throw;
+        }
+    }
+
+    /// Removes the files an earlier update left behind.
+    public static void DeleteOldFiles(string directory)
+    {
+        try
+        {
+            foreach (var file in Directory.EnumerateFiles(directory, "*" + OldFileSuffix, SearchOption.AllDirectories))
+            {
+                try
+                {
+                    File.Delete(file);
+                }
+                catch (Exception e) when (e is IOException or UnauthorizedAccessException)
+                {
+                    // still in use, the next run tries again
+                }
+            }
+        }
+        catch (Exception e) when (e is IOException or UnauthorizedAccessException)
+        {
+        }
+    }
+}