Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.<version>.nupkg`; install that file with
`dotnet tool install -g rta --add-source <folder with the nupkg> --version <version>`.

Expand All @@ -53,7 +54,7 @@ Update with `dotnet tool update -g rta`. The tool is also attached to every
1. Download `rta-v<version>-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).

Expand Down
195 changes: 195 additions & 0 deletions raidTimeline.App.Tests/UpdateServiceTests.cs
Original file line number Diff line number Diff line change
@@ -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<Uri, HttpResponseMessage> _respond;

public StubHandler(Func<Uri, HttpResponseMessage> respond) => _respond = respond;

protected override Task<HttpResponseMessage> 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<UpdateException>(() => 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<UpdateException>(() => 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<UpdateException>(() =>
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<UpdateException>(() =>
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<UpdateException>(() => 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<UpdateException>(() => 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;
}
}
124 changes: 124 additions & 0 deletions raidTimeline.App/Commands/UpdateCommands.cs
Original file line number Diff line number Diff line change
@@ -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<int> 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<int> 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;
}
}
1 change: 1 addition & 0 deletions raidTimeline.App/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,6 @@
app.RegisterFileCommands();
app.RegisterUploadCommands();
app.RegisterDatabaseCommands();
app.RegisterUpdateCommands();

app.Run();
Loading