Skip to content

Commit bdc0a0c

Browse files
**Refactor: clean up tests, models, and services; update ReadMe and UI logic**
- Simplify null handling, use collection expressions, const where possible - Remove unnecessary locks and improve cancellation token handling - Update SharpCompress to v0.48.0 and adjust timeout option order in ReadMe - Minor cleanups in AppHttpClient, PathUtils, and MainWindow
1 parent 7ffd24d commit bdc0a0c

13 files changed

Lines changed: 57 additions & 33 deletions

BatchConvertToCHD.Tests/BugReportServiceTests.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,11 +115,11 @@ public void GetExceptionStackTraceLimitsDepth()
115115
var method = typeof(BugReportService).GetMethod("GetExceptionStackTrace", BindingFlags.NonPublic | BindingFlags.Static);
116116
Assert.NotNull(method);
117117

118-
var inner = new Exception("deepest");
118+
var inner = new InvalidOperationException("deepest");
119119
var current = inner;
120120
for (var i = 0; i < 10; i++)
121121
{
122-
current = new Exception($"level {i}", current);
122+
current = new InvalidOperationException($"level {i}", current);
123123
}
124124

125125
var result = method.Invoke(null, [current]) as string;
@@ -154,7 +154,7 @@ public void AppendExceptionDetailsWithNullStackTraceDoesNotCrash()
154154
Assert.NotNull(method);
155155

156156
var sb = new StringBuilder();
157-
var ex = new Exception("No stack") { };
157+
var ex = new InvalidOperationException("No stack");
158158
var record = Record.Exception(() => method.Invoke(null, [sb, ex, 0]));
159159
Assert.Null(record);
160160
Assert.Contains("No stack", sb.ToString(), StringComparison.Ordinal);

BatchConvertToCHD.Tests/FileExtensionsTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ public class FileExtensionsTests
2424
public void ConstantHasCorrectValue(string expected, string constantName)
2525
{
2626
var actual = typeof(FileExtensions)
27-
.GetField(constantName)!
28-
.GetValue(null) as string;
27+
.GetField(constantName)
28+
?.GetValue(null) as string;
2929

3030
Assert.Equal(expected, actual);
3131
}

BatchConvertToCHD.Tests/GitHubReleaseTests.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ namespace BatchConvertToCHD.Tests;
55

66
public class GitHubReleaseTests
77
{
8+
private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true };
9+
810
[Fact]
911
public void DefaultValuesAreEmpty()
1012
{
@@ -51,7 +53,7 @@ public void DeserializeValidReleaseJson()
5153
}
5254
""";
5355

54-
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
56+
var options = JsonOptions;
5557
var release = JsonSerializer.Deserialize<GitHubRelease>(json, options);
5658

5759
Assert.NotNull(release);
@@ -77,7 +79,7 @@ public void DeserializePrereleaseJson()
7779
}
7880
""";
7981

80-
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
82+
var options = JsonOptions;
8183
var release = JsonSerializer.Deserialize<GitHubRelease>(json, options);
8284

8385
Assert.NotNull(release);
@@ -90,7 +92,7 @@ public void DeserializeMinimalJsonSetsDefaults()
9092
{
9193
const string json = "{}";
9294

93-
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
95+
var options = JsonOptions;
9496
var release = JsonSerializer.Deserialize<GitHubRelease>(json, options);
9597

9698
Assert.NotNull(release);

BatchConvertToCHD.Tests/PathUtilsTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ public void ValidateAndNormalizePathValidDirectoryReturnsNormalizedPath()
7979
public void ValidateAndNormalizePathNullPathReturnsNull()
8080
{
8181
string? capturedError = null;
82-
var result = PathUtils.ValidateAndNormalizePath(null!, "test folder", msg => { capturedError = msg; }, static _ => { });
82+
var result = PathUtils.ValidateAndNormalizePath(null, "test folder", msg => { capturedError = msg; }, static _ => { });
8383
Assert.Null(result);
8484
Assert.NotNull(capturedError);
8585
}
@@ -148,7 +148,7 @@ public void GetSafeTempFileNameSanitizesInput()
148148
[Fact]
149149
public void SanitizeFileNameAllInvalidCharsReplaced()
150150
{
151-
var input = "a<b>c:d\"e/f\\g|h?i*j";
151+
const string input = "a<b>c:d\"e/f\\g|h?i*j";
152152
var result = PathUtils.SanitizeFileName(input);
153153
Assert.DoesNotContain("<", result, StringComparison.Ordinal);
154154
Assert.DoesNotContain(">", result, StringComparison.Ordinal);

BatchConvertToCHD.Tests/PbpExtractionResultTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public void AllPropertiesCanBeSetTogether()
4444
var result = new PbpExtractionResult
4545
{
4646
Success = true,
47-
CueFilePaths = new List<string> { "game.cue" },
47+
CueFilePaths = ["game.cue"],
4848
OutputFolder = @"C:\extracted"
4949
};
5050
Assert.True(result.Success);

BatchConvertToCHD.Tests/StatsServiceTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public void ConstructorStoresParametersCorrectly()
3030
public async Task RecordUsageAsyncDoesNotThrowOnNetworkError()
3131
{
3232
var service = new StatsService("https://invalid.example.invalid/api", TestApiKey, TestAppId);
33-
var exception = await Record.ExceptionAsync(async () => await service.RecordUsageAsync());
33+
var exception = await Record.ExceptionAsync(service.RecordUsageAsync);
3434
Assert.Null(exception);
3535
}
3636
}

BatchConvertToCHD.Tests/UpdateServiceTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public void ParseVersionFromTagNullReturnsEmpty()
5353
var method = typeof(UpdateService).GetMethod("ParseVersionFromTag", BindingFlags.NonPublic | BindingFlags.Static);
5454
Assert.NotNull(method);
5555

56-
var result = method.Invoke(null, [null!]) as string;
56+
var result = method.Invoke(null, [null]) as string;
5757
Assert.Equal(string.Empty, result);
5858
}
5959
}

BatchConvertToCHD/App.xaml.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System.IO;
2-
using System.Threading;
32
using System.Windows;
43
using System.Windows.Threading;
54
using BatchConvertToCHD.Services;
@@ -43,7 +42,7 @@ public App()
4342

4443
protected override void OnStartup(StartupEventArgs e)
4544
{
46-
_singleInstanceMutex = new Mutex(true, $"Global\\{AppConfig.ApplicationName}_SingleInstance", out bool createdNew);
45+
_singleInstanceMutex = new Mutex(true, $"Global\\{AppConfig.ApplicationName}_SingleInstance", out var createdNew);
4746
if (!createdNew)
4847
{
4948
_singleInstanceMutex.Dispose();
@@ -170,6 +169,4 @@ private void ReportException(Exception exception, string source)
170169
// Silently ignore any errors in the reporting process
171170
}
172171
}
173-
174-
175172
}

BatchConvertToCHD/MainWindow.xaml.cs

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ namespace BatchConvertToCHD;
2020
public partial class MainWindow : IDisposable
2121
{
2222
private CancellationTokenSource _cts;
23-
private readonly object _ctsLock = new object();
23+
private readonly object _ctsLock = new();
2424
private readonly string _maxCsoPath;
2525
private readonly bool _isMaxCsoAvailable;
2626
private readonly bool _isChdmanAvailable;
@@ -499,7 +499,7 @@ private void DisplayExtractionInstructionsInLog()
499499

500500
private void MainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
501501
{
502-
if (e.Source is not TabControl)
502+
if (e.Source is not TabControl control)
503503
{
504504
return;
505505
}
@@ -510,7 +510,7 @@ private void MainTabControl_SelectionChanged(object sender, SelectionChangedEven
510510
}
511511

512512
Application.Current.Dispatcher.InvokeAsync((Action)(() => LogViewer.Clear()));
513-
if (((TabControl)e.Source).SelectedItem is TabItem selectedTab)
513+
if (control.SelectedItem is TabItem selectedTab)
514514
{
515515
switch (selectedTab.Name)
516516
{
@@ -691,8 +691,14 @@ private async void StartExtractionButton_ClickAsync(object sender, RoutedEventAr
691691

692692
try
693693
{
694+
CancellationToken token;
695+
lock (_ctsLock)
696+
{
697+
token = _cts.Token;
698+
}
699+
694700
await PerformBatchExtractionAsync(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppConfig.ChdmanExeName),
695-
inputFolder, outputFolder, deleteOriginal, selectedFiles, _cts.Token);
701+
inputFolder, outputFolder, deleteOriginal, selectedFiles, token);
696702
}
697703
catch (OperationCanceledException)
698704
{
@@ -1011,8 +1017,14 @@ private async void StartConversionButton_ClickAsync(object sender, RoutedEventAr
10111017

10121018
try
10131019
{
1020+
CancellationToken token;
1021+
lock (_ctsLock)
1022+
{
1023+
token = _cts.Token;
1024+
}
1025+
10141026
await PerformBatchConversionAsync(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppConfig.ChdmanExeName),
1015-
inputFolder, outputFolder, deleteFiles, processSmallerFirst, forceCd, forceDvd, timeoutMinutes, selectedFiles, _cts.Token);
1027+
inputFolder, outputFolder, deleteFiles, processSmallerFirst, forceCd, forceDvd, timeoutMinutes, selectedFiles, token);
10161028
}
10171029
catch (OperationCanceledException)
10181030
{
@@ -1078,8 +1090,14 @@ private async void StartVerificationButton_ClickAsync(object sender, RoutedEvent
10781090

10791091
try
10801092
{
1093+
CancellationToken token;
1094+
lock (_ctsLock)
1095+
{
1096+
token = _cts.Token;
1097+
}
1098+
10811099
await PerformBatchVerificationAsync(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppConfig.ChdmanExeName),
1082-
inputFolder, includeSubfolders, moveSuccess, successFolder, moveFailed, failedFolder, selectedFiles, _cts.Token);
1100+
inputFolder, includeSubfolders, moveSuccess, successFolder, moveFailed, failedFolder, selectedFiles, token);
10831101
}
10841102
catch (OperationCanceledException)
10851103
{
@@ -1130,6 +1148,7 @@ private void CancelButton_Click(object sender, RoutedEventArgs e)
11301148
{
11311149
_cts.Cancel();
11321150
}
1151+
11331152
LogMessage("Cancellation requested...");
11341153
UpdateStatusBarMessage("Cancelling...");
11351154
}
@@ -1496,7 +1515,7 @@ private async Task<bool> ProcessSingleFileForConversionAsync(string chdmanPath,
14961515
break;
14971516
}
14981517

1499-
var missingFiles = filesToCopy.Distinct().Where(f => !File.Exists(f)).ToList();
1518+
var missingFiles = filesToCopy.Distinct().Where(static f => !File.Exists(f)).ToList();
15001519
if (missingFiles.Count > 0)
15011520
{
15021521
var missingNames = string.Join(", ", missingFiles.Select(Path.GetFileName));
@@ -2715,6 +2734,7 @@ public void Dispose()
27152734
_cts.Cancel();
27162735
_cts.Dispose();
27172736
}
2737+
27182738
_writeBytesCounter?.Dispose();
27192739
_readBytesCounter?.Dispose();
27202740
_archiveService.Dispose();

BatchConvertToCHD/Models/FileItem.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName
120120
private static string FormatSize(long bytes)
121121
{
122122
string[] suffix = ["B", "KB", "MB", "GB", "TB"];
123-
int i = 0;
123+
var i = 0;
124124
double size = bytes;
125125
while (size >= 1024 && i < suffix.Length - 1)
126126
{

0 commit comments

Comments
 (0)