Skip to content

Commit

Permalink
chore: resolve build warnings after .NET 8.0 update
Browse files Browse the repository at this point in the history
  • Loading branch information
stranne committed Aug 15, 2024
1 parent 2413c12 commit 91d185c
Show file tree
Hide file tree
Showing 17 changed files with 56 additions and 51 deletions.
8 changes: 4 additions & 4 deletions GodotEnv.Tests/src/MainTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class MainTest {
[Fact]
public async Task CallsCliFx()
=> await Should.NotThrowAsync(
async () => await GodotEnv.Main(new string[] { "not-a-command" })
async () => await GodotEnv.Main(["not-a-command"])
);

[Fact]
Expand All @@ -24,8 +24,8 @@ public void CreateExecutionContextParsesArgs() {
args, config, workingDir, addonsContext.Object,
godotContext.Object
);
context.CliArgs.ShouldBe(new string[] { "a" });
context.CommandArgs.ShouldBe(new string[] { "b" });
context.CliArgs.ShouldBe(["a"]);
context.CommandArgs.ShouldBe(["b"]);
context.Config.ShouldBe(config);
context.WorkingDir.ShouldBe(workingDir);
context.Addons.ShouldBe(addonsContext.Object);
Expand All @@ -34,7 +34,7 @@ public void CreateExecutionContextParsesArgs() {
}

public class GodotEnvActivatorTest {
private class ITestCommand(IExecutionContext executionContext) :
private sealed class ITestCommand(IExecutionContext executionContext) :
ICliCommand {
public IExecutionContext ExecutionContext { get; } = executionContext;
}
Expand Down
19 changes: 10 additions & 9 deletions GodotEnv.Tests/src/common/clients/FileClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,9 @@ public void CombineCombinesPathComponents() {
fs.Setup(fs => fs.Path).Returns(path.Object);
path.Setup(path => path.DirectorySeparatorChar)
.Returns('/');
var expectedArgs = new[] { "a", "b" };
path.Setup(path => path.Combine(
It.Is<string[]>(args => args.SequenceEqual(new[] { "a", "b" })))
It.Is<string[]>(args => args.SequenceEqual(expectedArgs)))
).Returns("a/b");

var computer = new Mock<IComputer>();
Expand Down Expand Up @@ -366,11 +367,11 @@ public void FileThatExistsFindsFirstPossibleName() {
fs, computer.Object, new Mock<IProcessRunner>().Object
);

client.FileThatExists(new string[] { "0.txt", "b.txt", "a.txt" }, "/")
client.FileThatExists(["0.txt", "b.txt", "a.txt"], "/")
.ShouldBe("/b.txt");
client.FileThatExists(new string[] { "0.txt", "a.txt", "b.txt" }, "/")
client.FileThatExists(["0.txt", "a.txt", "b.txt"], "/")
.ShouldBe("/a.txt");
client.FileThatExists(new string[] { "0.txt", "1.txt" }, "/")
client.FileThatExists(["0.txt", "1.txt"], "/")
.ShouldBeNull();
}

Expand Down Expand Up @@ -462,7 +463,7 @@ public void ReadJsonFileReadsFromFirstFileItFounds() {

client.ReadJsonFile(
"",
new string[] { "model_a.json", "model_b.json" },
["model_a.json", "model_b.json"],
out var filename,
new TestJsonModel(name: "default")
).ShouldBe(new TestJsonModel(name: "test"));
Expand All @@ -484,7 +485,7 @@ public void ReadJsonFileThrowsIfDeserializedValueIsNull() {
var e = Should.Throw<IOException>(
() => client.ReadJsonFile(
"",
new string[] { "model.json" },
["model.json"],
out var filename,
new TestJsonModel(name: "default")
)
Expand All @@ -507,7 +508,7 @@ public void ReadJsonFileThrowsIOExceptionOnOtherError() {
Should.Throw<IOException>(
() => client.ReadJsonFile(
"",
new string[] { "model.json", "model_a.json", "model_b.json" },
["model.json", "model_a.json", "model_b.json"],
out var filename,
new TestJsonModel(name: "default")
)
Expand All @@ -527,7 +528,7 @@ public void ReadJsonFileChecksOtherPossibleFilenames() {

client.ReadJsonFile(
"",
new string[] { "model.json", "model_a.json", "model_b.json" },
["model.json", "model_a.json", "model_b.json"],
out var filename,
new TestJsonModel(name: "default")
).ShouldBe(new TestJsonModel(name: "alternative"));
Expand All @@ -546,7 +547,7 @@ public void ReadJsonFileReturnsDefaultValues() {

client.ReadJsonFile(
"",
new string[] { "model.json", "model_a.json", "model_b.json" },
["model.json", "model_a.json", "model_b.json"],
out var filename,
new TestJsonModel(name: "default")
).ShouldBe(new TestJsonModel(name: "default"));
Expand Down
4 changes: 2 additions & 2 deletions GodotEnv.Tests/src/common/utilities/ProcessRunnerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class ProcessRunnerTest {
public async Task RunsProcessOnWindows() {
var runner = new ProcessRunner();
var result = await runner.Run(
Environment.CurrentDirectory, "cmd", new[] { "/c echo \"hello\"" }
Environment.CurrentDirectory, "cmd", ["/c echo \"hello\""]
);
result.ExitCode.ShouldBe(0);
result.Succeeded.ShouldBe(true);
Expand All @@ -21,7 +21,7 @@ public async Task RunsProcessOnWindows() {
public async Task RunsProcessOnMacLinux() {
var runner = new ProcessRunner();
var result = await runner.Run(
Environment.CurrentDirectory, "echo", new[] { "hello" }
Environment.CurrentDirectory, "echo", ["hello"]
);
result.ExitCode.ShouldBe(0);
result.Succeeded.ShouldBe(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@ public void LoadsAddonsFile() {

var value = new AddonsFile();

var expectedArgs = new[] { "addons.json", "addons.jsonc" };
fileClient.Setup(client => client.ReadJsonFile(
projectPath,
It.Is<string[]>(
value => value.SequenceEqual(
new string[] { "addons.json", "addons.jsonc" }
)
value => value.SequenceEqual(expectedArgs)
),
out filename,
It.IsAny<AddonsFile>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace Chickensoft.GodotEnv.Tests;
using Xunit;

public class AddonsRepositoryTest {
private class Subject(
private sealed class Subject(
IConsole console,
Mock<IFileClient> client,
Mock<ILog> log,
Expand Down
2 changes: 1 addition & 1 deletion GodotEnv/src/common/clients/EnvironmentVariableClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ public async Task<string> GetUserDefaultShell() {
}

public bool IsShellSupported(string shellName) => FileClient.OS switch {
OSType.MacOS or OSType.Linux => SUPPORTED_UNIX_SHELLS.Contains(shellName.ToLower()),
OSType.MacOS or OSType.Linux => SUPPORTED_UNIX_SHELLS.Contains(shellName.ToLowerInvariant()),
OSType.Windows => true,
OSType.Unknown => false,
_ => false,
Expand Down
6 changes: 3 additions & 3 deletions GodotEnv/src/common/clients/FileClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -627,10 +627,10 @@ public void AddLinesToFileIfNotPresent(
var existingLines = ReadLines(filePath);

var compareLines = existingLines
.Select(line => line.ToLower().Trim()).ToHashSet();
.Select(line => line.ToLowerInvariant().Trim()).ToHashSet();

var newLines = lines.Where(
line => !compareLines.Contains(line.ToLower().Trim())
line => !compareLines.Contains(line.ToLowerInvariant().Trim())
);

WriteLines(filePath, existingLines.Concat(newLines));
Expand All @@ -640,7 +640,7 @@ public string FindLineBeginningWithPrefix(string filePath, string prefix) {
if (!Files.File.Exists(filePath)) { return ""; }

foreach (var line in ReadLines(filePath)) {
if (line.Trim().ToLower().StartsWith(prefix.Trim().ToLower())) {
if (line.Trim().StartsWith(prefix.Trim(), StringComparison.InvariantCultureIgnoreCase)) {
return line;
}
}
Expand Down
8 changes: 5 additions & 3 deletions GodotEnv/src/common/clients/ZipClientTerminal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ namespace Chickensoft.GodotEnv.Common.Clients;
using System.Threading.Tasks;
using Chickensoft.GodotEnv.Common.Utilities;

public class ZipClientTerminal : IZipClient {
public partial class ZipClientTerminal : IZipClient {
public IComputer Computer { get; }
public IFileSystem Files { get; }

public static readonly Regex NumFilesRegex =
new(@"\s*(?<numFiles>\d+)\s+files?");
public static readonly Regex NumFilesRegex = numFilesRegex();

public ZipClientTerminal(IComputer computer, IFileSystem files) {
Computer = computer;
Expand Down Expand Up @@ -50,4 +49,7 @@ await shell.RunWithUpdates(

log.Print($"🗜 Extracted {numEntries} / {numFiles} files in {sourceArchiveFileName}.");
}

[GeneratedRegex(@"\s*(?<numFiles>\d+)\s+files?")]
private static partial Regex numFilesRegex();
}
2 changes: 1 addition & 1 deletion GodotEnv/src/common/domain/ConfigFileRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public ConfigFileRepository(IFileClient fileClient) {
public ConfigFile LoadConfigFile(out string filename) =>
FileClient.ReadJsonFile(
projectPath: FileClient.AppDataDirectory,
possibleFilenames: new string[] { Defaults.CONFIG_FILE_NAME },
possibleFilenames: [Defaults.CONFIG_FILE_NAME],
filename: out filename,
defaultValue: new ConfigFile()
);
Expand Down
10 changes: 5 additions & 5 deletions GodotEnv/src/common/models/Asset.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public enum AssetSource {
/// <summary>
/// Represents a resource accessed via a remote path, local path, or symlink.
/// </summary>
public interface IAsset {
public partial interface IAsset {
/// <summary>
/// Asset path if <see cref="Source" /> is <see cref="AssetSource.Local" />
/// or <see cref="AssetSource.Symlink" />. Otherwise, if
Expand Down Expand Up @@ -72,10 +72,10 @@ string Id {
/// git repository url. <br />
/// Credit: https://serverfault.com/a/917253
/// </summary>
public static readonly Regex UrlRegex = new(
@"^((https?|ssh|git|ftps?|git\+ssh|git\+https):\/\/)?(([^\/@]+)@)?" +
@"([^\/:]+)[\/:]([^\/:]+)\/(.+).git\/?$"
);
public static readonly Regex UrlRegex = urlRegex();

[GeneratedRegex(@"^((https?|ssh|git|ftps?|git\+ssh|git\+https):\/\/)?(([^\/@]+)@)?([^\/:]+)[\/:]([^\/:]+)\/(.+).git\/?$")]
private static partial Regex urlRegex();
}

/// <summary>
Expand Down
4 changes: 3 additions & 1 deletion GodotEnv/src/features/addons/domain/AddonsFileRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,16 @@ AddonsConfiguration CreateAddonsConfiguration(
public class AddonsFileRepository : IAddonsFileRepository {
public IFileClient FileClient { get; }

private static readonly string[] possibleFilenames = ["addons.json", "addons.jsonc"];

public AddonsFileRepository(IFileClient fileClient) {
FileClient = fileClient;
}

public AddonsFile LoadAddonsFile(string projectPath, out string filename) =>
FileClient.ReadJsonFile(
projectPath: projectPath,
possibleFilenames: new string[] { "addons.json", "addons.jsonc" },
possibleFilenames: possibleFilenames,
filename: out filename,
defaultValue: new AddonsFile()
);
Expand Down
4 changes: 3 additions & 1 deletion GodotEnv/src/features/addons/models/Addon.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ public record Addon : Asset, IAddon {
/// <inheritdoc />
public string Subfolder { get; init; }

private static readonly char[] trimChars = ['/', '\\'];

/// <summary>
/// Create a new representation of a resolved addon.
/// </summary>
Expand All @@ -53,7 +55,7 @@ AssetSource source
) : base(url, checkout, source) {
Name = name;
AddonsFilePath = addonsFilePath;
Subfolder = subfolder.Trim(new char[] { '/', '\\' });
Subfolder = subfolder.Trim(trimChars);
}

public override string ToString()
Expand Down
4 changes: 2 additions & 2 deletions GodotEnv/src/features/godot/domain/GodotChecksumClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Chickensoft.GodotEnv.Features.Godot.Domain;
namespace Chickensoft.GodotEnv.Features.Godot.Domain;

using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -90,7 +90,7 @@ private record FileChecksumData {
public async Task<string> ComputeChecksumOfArchive(GodotCompressedArchive archive) {
using var sha512 = SHA512.Create();
await using var filestream = File.OpenRead(Path.Join(archive.Path, archive.Filename));
return Convert.ToHexString(await sha512.ComputeHashAsync(filestream)).ToLower();
return Convert.ToHexString(await sha512.ComputeHashAsync(filestream)).ToLowerInvariant();
}
}

Expand Down
10 changes: 5 additions & 5 deletions GodotEnv/src/features/godot/domain/GodotRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ Task<bool> Uninstall(
);
}

public class GodotRepository : IGodotRepository {
public partial class GodotRepository : IGodotRepository {
public ConfigFile Config { get; }
public IFileClient FileClient { get; }
public INetworkClient NetworkClient { get; }
Expand Down Expand Up @@ -171,10 +171,7 @@ public IEnvironmentVariableClient EnvironmentVariableClient {

// Regex for converting directory names back into version strings to see
// what versions we have installed.
public static readonly Regex DirectoryToVersionStringRegex = new(
@"godot_(dotnet_)?(?<major>\d+)_(?<minor>\d+)_(?<patch>\d+)_?(?<label>[a-zA-Z]+_?[\d]+)?",
RegexOptions.Compiled | RegexOptions.IgnoreCase
);
public static readonly Regex DirectoryToVersionStringRegex = directoryToVersionStringRegex();

public GodotRepository(
ConfigFile config,
Expand Down Expand Up @@ -684,4 +681,7 @@ private string GetVersionFsName(
($"godot_{(isDotnetVersion ? "dotnet_" : "")}" +
$"{version.Major}_{version.Minor}_{version.Patch}_" +
$"{LabelSanitized(version)}").Trim('_');

[GeneratedRegex(@"godot_(dotnet_)?(?<major>\d+)_(?<minor>\d+)_(?<patch>\d+)_?(?<label>[a-zA-Z]+_?[\d]+)?", RegexOptions.IgnoreCase | RegexOptions.Compiled, "en-US")]
private static partial Regex directoryToVersionStringRegex();
}
8 changes: 3 additions & 5 deletions GodotEnv/src/features/godot/models/GodotEnvironment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ public async Task<List<IFileInfo>> FindExecutablesRecursively(
},
dirSelector: (dirInfo) => {
// Don't look for debug executables.
var name = dirInfo.Name.ToLower();
var name = dirInfo.Name.ToLowerInvariant();
if (name.Contains("debug") || name.EndsWith(".lproj")) {
return Task.FromResult(false);
}
Expand Down Expand Up @@ -319,8 +319,6 @@ private static string GetExportTemplatesInstallerFilename(
) => GetFilenameVersionString(version) + (isDotnetVersion ? "_mono" : "") +
"_export_templates.tpz";

private static Exception GetUnknownOSException() =>
new InvalidOperationException(
"🚨 Cannot create a platform an unknown operating system."
);
private static InvalidOperationException GetUnknownOSException() =>
new("🚨 Cannot create a platform an unknown operating system.");
}
9 changes: 5 additions & 4 deletions GodotEnv/src/features/godot/models/SemanticVersion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ namespace Chickensoft.GodotEnv.Features.Godot.Models;
using System;
using System.Text.RegularExpressions;

public record SemanticVersion(
public partial record SemanticVersion(
string Major, string Minor, string Patch, string Label = ""
) {
// Borrowed from https://semver.org/
Expand All @@ -13,9 +13,7 @@ public record SemanticVersion(
/// <br />
/// Try it: https://regex101.com/r/vkijKf/1/
/// </summary>
public static Regex SemanticVersionRegex { get; } = new(
@"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$"
);
public static Regex SemanticVersionRegex { get; } = semanticVersionRegex();

/// <summary>
/// Parses a string into a semantic version model using the official
Expand Down Expand Up @@ -75,4 +73,7 @@ public string Format(bool omitPatchIfZero, bool noDotsInLabel) {

public override string ToString() =>
$"Major({Major}).Minor({Minor}).Patch({Patch})-Label({Label})";

[GeneratedRegex(@"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$")]
private static partial Regex semanticVersionRegex();
}
2 changes: 1 addition & 1 deletion GodotEnv/src/features/godot/models/Windows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public override string GetInstallerNameSuffix(bool isDotnetVersion, SemanticVers
isDotnetVersion ? "_mono_win64" : "_win64.exe";

public override Task<bool> IsExecutable(IShell shell, IFileInfo file) =>
Task.FromResult(file.Name.ToLower().EndsWith(".exe"));
Task.FromResult(file.Name.ToLowerInvariant().EndsWith(".exe"));

public override void Describe(ILog log) => log.Info("⧉ Running on Windows");

Expand Down

0 comments on commit 91d185c

Please sign in to comment.