fix: findings of the first Qodana analysis
High-severity findings in the shipped code: - HashEngine disposes exactly the hash functions it created (a list instead of an array with null checks). - SingleInstance allocates the pipe header once, not on the stack in every retry, and AllowSetForegroundWindow's unused result is no longer declared. - Lambdas whose first parameter was named "_" assigned tasks to that parameter instead of discarding them (UnhandledException handler, settings save timer). - ChecksumWriter sets the writer's NewLine after the using declaration; LocalizationService raises the indexer change without a caller-info argument; VerifyCommand's Outcome drops a field nobody read. - Nullability: converters return non-null values, the language combo box may set null, FocusManager is never null. - Redundant usings (global usings of the app), qualifiers and default arguments; C# 14 lambda parameters. - FocusHandOff, RowTabNavigation and HighlightTextBlock move to Views/Controls, matching their namespace. qodana.yaml analyses the shipped code (tests and benchmarks are covered by the build, analyzers and SonarCloud), leaves Roslyn analyzer suggestions to the build, documents each remaining exclusion, and fails on critical or high findings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
eca13e45dc
commit
9c91f5f01d
32 files changed
+99
-65
No files matched your search
+52
-5
@@ -5,14 +5,61 @@ version: "1.0"
|
||||
linter: qodana-dotnet
|
||||
withinDocker: false
|
||||
|
||||
profile:
|
||||
name: qodana.recommended
|
||||
|
||||
dotnet:
|
||||
solution: HashTool.slnx
|
||||
|
||||
# The shipped code. Tests and benchmarks are checked by the compiler, the analyzers and SonarCloud; the legacy client is
|
||||
# pinned to Velopack 0.0.1298 on purpose (the release upgrade gate runs it like a Hash Tool 1.1.x client).
|
||||
exclude:
|
||||
- name: All
|
||||
paths:
|
||||
# Pinned to Velopack 0.0.1298 on purpose: the release upgrade gate runs it like a Hash Tool 1.1.x client.
|
||||
- tests/Compat
|
||||
- tests
|
||||
- bench
|
||||
|
||||
profile:
|
||||
base:
|
||||
name: qodana.recommended
|
||||
groups:
|
||||
- groupId: RoslynAnalyzers
|
||||
groups:
|
||||
- "category:C#/Roslyn Analyzers"
|
||||
inspections:
|
||||
# Roslyn analyzers (Meziantou, .NET, CommunityToolkit.Mvvm) already run in every build, where their warnings fail
|
||||
# CI; their suggestions are not repeated here (SonarCloud ignores them too).
|
||||
- group: RoslynAnalyzers
|
||||
enabled: false
|
||||
# Translations may equal the English text: en-GB/en-IN/en-SG, product and technical names.
|
||||
- inspection: OverriddenWithSameValue
|
||||
ignore:
|
||||
- "src/HashTool.App/Lang/**"
|
||||
# Compiled bindings such as $parent[Window].((vm:MainWindowViewModel)DataContext).X: the data context is set by the
|
||||
# view that hosts the control.
|
||||
- inspection: Xaml.PossibleNullReferenceException
|
||||
enabled: false
|
||||
# "accent" comes from the Fluent theme; "hashInput" marks the expected-hash box for code-behind.
|
||||
- inspection: Xaml.StyleClassNotFound
|
||||
enabled: false
|
||||
# OnXChanged(value) partial methods are declared by CommunityToolkit.Mvvm's generator.
|
||||
- inspection: UnusedParameterInPartialMethod
|
||||
enabled: false
|
||||
# Drag and drop handlers must be async void; their exceptions reach Dispatcher.UIThread.UnhandledException.
|
||||
- inspection: AsyncVoidLambda
|
||||
ignore:
|
||||
- "src/HashTool.App/Views/**"
|
||||
# The application manifest uses the Windows side-by-side schema, which the XML checker does not know.
|
||||
- inspection: XmlHighlighting
|
||||
ignore:
|
||||
- "src/HashTool.App/app.manifest"
|
||||
# Avalonia's application class, completed by the XAML compiler.
|
||||
- inspection: PartialTypeWithSinglePart
|
||||
ignore:
|
||||
- "src/HashTool.App/App.axaml.cs"
|
||||
# The smoke test cancels the token from a continuation that runs before the dispatcher loop returns.
|
||||
- inspection: AccessToDisposedClosure
|
||||
ignore:
|
||||
- "src/HashTool.App/Infrastructure/SmokeTest.cs"
|
||||
|
||||
failureConditions:
|
||||
severityThresholds:
|
||||
critical: 0
|
||||
high: 0
|
||||
@@ -36,7 +36,7 @@ public partial class App : Application
|
||||
};
|
||||
}
|
||||
|
||||
Dispatcher.UIThread.UnhandledException += (_, e) =>
|
||||
Dispatcher.UIThread.UnhandledException += (sender, e) =>
|
||||
{
|
||||
logger.LogError(e.Exception, "Unhandled UI exception");
|
||||
e.Handled = true;
|
||||
|
||||
@@ -4,8 +4,6 @@ using HashTool.App.Infrastructure.Logging;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.Services.Theme;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core.Configuration;
|
||||
using HashTool.Core.Hashing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
|
||||
@@ -17,6 +17,6 @@ public sealed class FontNameConverter : IValueConverter
|
||||
_ => value
|
||||
};
|
||||
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
@@ -7,9 +7,9 @@ namespace HashTool.App.Converters;
|
||||
|
||||
public class HashMaskConverter : IMultiValueConverter
|
||||
{
|
||||
public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
|
||||
public object Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (values == null || values.Count < 3) return "";
|
||||
if (values.Count < 3) return "";
|
||||
|
||||
var hash = values[0] as string ?? "";
|
||||
var isMaskingEnabled = values[1] as bool? ?? false;
|
||||
|
||||
@@ -5,7 +5,6 @@ using Avalonia.Data.Converters;
|
||||
using HashTool.App.Models;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core.Configuration;
|
||||
|
||||
namespace HashTool.App.Converters;
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using HashTool.Core.Configuration;
|
||||
|
||||
namespace HashTool.App.Infrastructure;
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ public sealed partial class SingleInstance : IDisposable
|
||||
request ??= new ActivationRequest(ActivationVerb.Auto, []);
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
var delay = 50;
|
||||
Span<byte> header = stackalloc byte[4];
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
try
|
||||
@@ -75,7 +76,6 @@ public sealed partial class SingleInstance : IDisposable
|
||||
client.Connect(Math.Max(100, (int)(deadline - DateTime.UtcNow).TotalMilliseconds));
|
||||
if (OperatingSystem.IsWindows()) AllowSetForegroundWindow(-1);
|
||||
var payload = JsonSerializer.SerializeToUtf8Bytes(new PipeMessage(request.Verb, [.. request.Paths]), PipeJsonContext.Default.PipeMessage);
|
||||
Span<byte> header = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteInt32LittleEndian(header, payload.Length);
|
||||
client.Write(header);
|
||||
client.Write(payload);
|
||||
@@ -180,9 +180,9 @@ public sealed partial class SingleInstance : IDisposable
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
// Returns whether it worked; there is nothing to do when it did not.
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool AllowSetForegroundWindow(int processId);
|
||||
private static partial void AllowSetForegroundWindow(int processId);
|
||||
|
||||
/// <summary>Wire format; a single constructor so the source-generated serializer can create it.</summary>
|
||||
internal sealed record PipeMessage(ActivationVerb Verb, string[] Paths);
|
||||
|
||||
@@ -82,7 +82,7 @@ public static class SmokeTest
|
||||
// Hash a text.
|
||||
main.Text.Text = "123456789";
|
||||
await main.Text.Pending;
|
||||
var textHash = main.Text.Results.Single(r => r.Algorithm == Core.Hashing.HashType.SHA256).Hash;
|
||||
var textHash = main.Text.Results.Single(r => r.Algorithm == HashType.SHA256).Hash;
|
||||
if (!string.Equals(textHash, Sha256Of123456789, StringComparison.OrdinalIgnoreCase))
|
||||
report.Errors.Add($"Text: unexpected hash {textHash}");
|
||||
|
||||
@@ -110,7 +110,7 @@ public static class SmokeTest
|
||||
{
|
||||
var file = Path.Combine(folder.FullName, "check.txt");
|
||||
await File.WriteAllTextAsync(file, "123456789");
|
||||
main.Create.SelectedAlgorithm = Core.Hashing.HashType.SHA256;
|
||||
main.Create.SelectedAlgorithm = HashType.SHA256;
|
||||
await main.Create.AddPathsAsync([file]);
|
||||
await main.Create.RunAllCommand.ExecuteAsync(null);
|
||||
var created = main.Create.Items.Single();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
@@ -42,6 +43,9 @@ internal sealed record LanguageEntry(string Name, string Code);
|
||||
/// </summary>
|
||||
public sealed partial class LocalizationService : ObservableObject
|
||||
{
|
||||
/// <summary>Raised for <c>Localization[Key]</c> bindings: every translated string may have changed.</summary>
|
||||
private static readonly PropertyChangedEventArgs IndexerChanged = new("Item[]");
|
||||
|
||||
private static readonly Dictionary<string, string> PreferredVariants = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["zh"] = "zh-Hans-CN",
|
||||
@@ -153,7 +157,7 @@ public sealed partial class LocalizationService : ObservableObject
|
||||
Culture = ApplyCulture(code);
|
||||
_cache.Clear();
|
||||
RefreshAutoName();
|
||||
OnPropertyChanged("Item[]");
|
||||
OnPropertyChanged(IndexerChanged);
|
||||
LanguageChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using HashTool.Core.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace HashTool.App.Services;
|
||||
@@ -26,7 +25,7 @@ public sealed class SettingsService : IDisposable
|
||||
_logger = logger;
|
||||
LoadResult = store.Load(out var settings);
|
||||
Current = settings;
|
||||
_saveTimer = new Timer(_ => _ = SaveNowAsync(), null, Timeout.Infinite, Timeout.Infinite);
|
||||
_saveTimer = new Timer(state => _ = SaveNowAsync(), null, Timeout.Infinite, Timeout.Infinite);
|
||||
_logger.LogInformation("Settings {Result} from {Path}", LoadResult, store.FilePath);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Avalonia.Media;
|
||||
using HashTool.Core.Configuration;
|
||||
|
||||
namespace HashTool.App.Services.Theme;
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ using Avalonia.Platform;
|
||||
using Avalonia.Styling;
|
||||
using Avalonia.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using HashTool.Core.Configuration;
|
||||
|
||||
namespace HashTool.App.Services.Theme;
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ public sealed partial class AboutViewModel : ObservableObject
|
||||
Library("Avalonia UI", typeof(Avalonia.Application), "MIT", "https://avaloniaui.net/"),
|
||||
Library("Inter font", typeof(Avalonia.Fonts.Inter.InterFontCollection), "SIL OFL 1.1", "https://rsms.me/inter/"),
|
||||
Library("Blake3.NET", typeof(Blake3.Hasher), "BSD-2-Clause", "https://github.com/xoofx/Blake3.NET"),
|
||||
Library("CommunityToolkit.Mvvm", typeof(CommunityToolkit.Mvvm.ComponentModel.ObservableObject), "MIT", "https://github.com/CommunityToolkit/dotnet"),
|
||||
Library("CommunityToolkit.Mvvm", typeof(ObservableObject), "MIT", "https://github.com/CommunityToolkit/dotnet"),
|
||||
Library("Material.Icons.Avalonia", typeof(Material.Icons.Avalonia.MaterialIcon), "MIT", "https://github.com/SKProCH/Material.Icons"),
|
||||
Library("Microsoft.Extensions.*", typeof(Microsoft.Extensions.Logging.ILogger), "MIT", "https://github.com/dotnet/runtime"),
|
||||
Library("System.IO.Hashing", typeof(System.IO.Hashing.XxHash3), "MIT", "https://github.com/dotnet/runtime"),
|
||||
|
||||
@@ -10,7 +10,6 @@ using HashTool.App.Models;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Files;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Processing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ using HashTool.App.Models;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Files;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Processing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@@ -89,7 +88,7 @@ public sealed partial class CreateHashViewModel : FileListViewModelBase
|
||||
var items = ItemsWithResults();
|
||||
if (items.Count == 0)
|
||||
{
|
||||
await Services.Dialogs.ShowAsync(L["Msg_Result_Title"], L["Msg_NothingToExport"], DialogIcon.Information);
|
||||
await Services.Dialogs.ShowAsync(L["Msg_Result_Title"], L["Msg_NothingToExport"]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -104,7 +103,7 @@ public sealed partial class CreateHashViewModel : FileListViewModelBase
|
||||
types.Add(new FileTypeChoice(L["FileType_Json"], "*.json", ExportFormat.Json));
|
||||
types.Add(new FileTypeChoice(L["FileType_Csv"], "*.csv", ExportFormat.Csv));
|
||||
|
||||
var preferred = types.FirstOrDefault(t => (ExportFormat)t.Tag! == Settings.DefaultExportFormat) ?? types[0];
|
||||
var preferred = types.FirstOrDefault(type => (ExportFormat)type.Tag! == Settings.DefaultExportFormat) ?? types[0];
|
||||
types.Remove(preferred);
|
||||
types.Insert(0, preferred);
|
||||
var format = (ExportFormat)preferred.Tag!;
|
||||
@@ -135,7 +134,7 @@ public sealed partial class CreateHashViewModel : FileListViewModelBase
|
||||
var items = ItemsWithResults();
|
||||
if (items.Count == 0)
|
||||
{
|
||||
await Services.Dialogs.ShowAsync(L["Msg_Result_Title"], L["Msg_NothingToExport"], DialogIcon.Information);
|
||||
await Services.Dialogs.ShowAsync(L["Msg_Result_Title"], L["Msg_NothingToExport"]);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@ public sealed partial class DeveloperViewModel : ObservableObject
|
||||
private readonly IStorageService _storage;
|
||||
private readonly ILauncherService _launcher;
|
||||
private readonly ConcurrentQueue<LogEntry> _incoming = new();
|
||||
private readonly DispatcherTimer _timer;
|
||||
|
||||
[ObservableProperty] private LocalizationProxy _localization;
|
||||
[ObservableProperty] private LogLevel _minimumLevel = LogLevel.Debug;
|
||||
@@ -42,8 +41,8 @@ public sealed partial class DeveloperViewModel : ObservableObject
|
||||
|
||||
Entries.AddRange(sink.Snapshot());
|
||||
sink.EntryAdded += (_, e) => _incoming.Enqueue(e.Entry);
|
||||
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Flush());
|
||||
_timer.Start();
|
||||
// The dispatcher keeps a running timer alive.
|
||||
new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Flush()).Start();
|
||||
}
|
||||
|
||||
/// <summary>Entries at or above <see cref="MinimumLevel"/>, newest last.</summary>
|
||||
|
||||
@@ -3,7 +3,6 @@ using System.IO;
|
||||
using System.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using HashTool.App.Models;
|
||||
using HashTool.Core.Hashing;
|
||||
|
||||
namespace HashTool.App.ViewModels;
|
||||
|
||||
@@ -58,7 +57,7 @@ public sealed partial class FileItem : ObservableObject
|
||||
|
||||
public long Size { get; }
|
||||
|
||||
public string SizeText => Core.ByteSize.Format(Size);
|
||||
public string SizeText => ByteSize.Format(Size);
|
||||
|
||||
[ObservableProperty] private HashType _algorithm;
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Models;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.Core.Files;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Processing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@@ -113,7 +112,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob
|
||||
|
||||
protected LocalizationService L => Services.Localization;
|
||||
|
||||
protected Core.Configuration.AppSettings Settings => Services.Settings.Current;
|
||||
protected AppSettings Settings => Services.Settings.Current;
|
||||
|
||||
/// <summary>Visible (filtered) items.</summary>
|
||||
public AvaloniaList<FileItem> Items { get; } = [];
|
||||
@@ -527,7 +526,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob
|
||||
protected async Task OfferElevationAsync(IReadOnlyList<FileItem> items)
|
||||
{
|
||||
if (!Elevation.CanRestartElevated || !items.Any(i => i.Status == ItemStatus.AccessDenied)) return;
|
||||
if (!await Services.Dialogs.ConfirmAsync(L["Btn_RestartAdmin"], L["Msg_AccessDeniedRestart"], DialogIcon.Question)) return;
|
||||
if (!await Services.Dialogs.ConfirmAsync(L["Btn_RestartAdmin"], L["Msg_AccessDeniedRestart"])) return;
|
||||
if (Elevation.RestartElevated(ElevationVerb, _all.Select(i => SourcePathForRestart(i)).Distinct(_byPath.Comparer).ToList()))
|
||||
RequestShutdown?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.Services.Theme;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Configuration;
|
||||
|
||||
namespace HashTool.App.ViewModels;
|
||||
|
||||
|
||||
@@ -4,16 +4,12 @@ using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Media;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Infrastructure.Logging;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.Services.Theme;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Configuration;
|
||||
using HashTool.Core.Hashing;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace HashTool.App.ViewModels;
|
||||
@@ -111,7 +107,7 @@ public sealed partial class SettingsViewModel : ObservableObject
|
||||
|
||||
// ------------------------------------------------------------------ language & appearance
|
||||
|
||||
public LanguageItem SelectedLanguage
|
||||
public LanguageItem? SelectedLanguage
|
||||
{
|
||||
get => Loc.SelectedLanguage;
|
||||
set
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ public static class FocusHandOff
|
||||
// The target usually becomes visible in the same update, possibly after this control was hidden.
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
var focused = topLevel.FocusManager?.GetFocusedElement();
|
||||
var focused = topLevel.FocusManager.GetFocusedElement();
|
||||
if ((focused is null || ReferenceEquals(focused, topLevel)) && ReferenceEquals(TopLevel.GetTopLevel(target), topLevel) &&
|
||||
target.IsEffectivelyVisible && target.IsEffectivelyEnabled)
|
||||
target.Focus(NavigationMethod.Tab);
|
||||
File renamed without changes.
File renamed without changes.
+1
-1
@@ -33,7 +33,7 @@ public static class RowTabNavigation
|
||||
private static void OnKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Handled || e.Key != Key.Tab || (e.KeyModifiers & ~KeyModifiers.Shift) != KeyModifiers.None) return;
|
||||
if (TopLevel.GetTopLevel(sender as Visual)?.FocusManager?.GetFocusedElement() is not Control focused) return;
|
||||
if (TopLevel.GetTopLevel(sender as Visual)?.FocusManager.GetFocusedElement() is not Control focused) return;
|
||||
var row = focused as ListBoxItem ?? focused.FindAncestorOfType<ListBoxItem>();
|
||||
if (row is null) return;
|
||||
|
||||
@@ -3,7 +3,6 @@ using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.Core.Configuration;
|
||||
|
||||
namespace HashTool.App.Views;
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Hashing;
|
||||
|
||||
namespace HashTool.Cli;
|
||||
|
||||
@@ -132,7 +132,7 @@ internal static class VerifyCommand
|
||||
|
||||
private static string Count(int count, string singular, string plural) => $"{count} {(count == 1 ? singular : plural)}";
|
||||
|
||||
internal readonly record struct Outcome(HashMatch Match, HashType? Algorithm, Exception? Error)
|
||||
internal readonly record struct Outcome(HashMatch Match, Exception? Error)
|
||||
{
|
||||
public bool IsOk => Error is null && Match is HashMatch.Match or HashMatch.LegacyByteOrderMatch;
|
||||
|
||||
@@ -151,7 +151,7 @@ internal static class VerifyCommand
|
||||
internal static async Task<Outcome> CheckAsync(HashEngine engine, string path, string expected, IReadOnlyList<HashType> candidates,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (candidates.Count == 0) return new Outcome(HashMatch.LengthMismatch, null, null);
|
||||
if (candidates.Count == 0) return new Outcome(HashMatch.LengthMismatch, null);
|
||||
HashResult[] results;
|
||||
try
|
||||
{
|
||||
@@ -159,13 +159,13 @@ internal static class VerifyCommand
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return new Outcome(HashMatch.Mismatch, null, ex);
|
||||
return new Outcome(HashMatch.Mismatch, ex);
|
||||
}
|
||||
|
||||
var matches = results.Select(r => (Result: r, Match: HashMatcher.Compare(expected, r))).ToList();
|
||||
var best = matches.FirstOrDefault(m => m.Match == HashMatch.Match);
|
||||
if (best.Result is null) best = matches.FirstOrDefault(m => m.Match == HashMatch.LegacyByteOrderMatch);
|
||||
if (best.Result is null) best = matches[0];
|
||||
return new Outcome(best.Match, best.Result.Algorithm, null);
|
||||
return new Outcome(best.Match, null);
|
||||
}
|
||||
}
|
||||
@@ -196,7 +196,7 @@ public static partial class ChecksumParser
|
||||
hash = HashMatcher.Normalize(hash);
|
||||
if (!HashMatcher.IsHex(hash)) return false;
|
||||
|
||||
HashType? algorithm = null;
|
||||
HashType algorithm;
|
||||
var guessed = false;
|
||||
if (explicitType is { } e && HashAlgorithms.HexLength(e) == hash.Length) algorithm = e;
|
||||
else if (explicitType is not null) return false;
|
||||
|
||||
@@ -29,7 +29,8 @@ public static class ChecksumWriter
|
||||
{
|
||||
public static string Write(IEnumerable<ChecksumLine> lines, ExportFormat format, HexCase letterCase = HexCase.Lower)
|
||||
{
|
||||
using var writer = new StringWriter(CultureInfo.InvariantCulture) { NewLine = "\n" };
|
||||
using var writer = new StringWriter(CultureInfo.InvariantCulture);
|
||||
writer.NewLine = "\n";
|
||||
Write(writer, lines, format, letterCase);
|
||||
return writer.ToString();
|
||||
}
|
||||
|
||||
@@ -72,10 +72,10 @@ public static class FileEnumerator
|
||||
try
|
||||
{
|
||||
enumerator = new FileSystemEnumerable<FileEntry>(Path.GetFullPath(directory),
|
||||
static (ref FileSystemEntry entry) => new FileEntry(entry.ToFullPath(), entry.Length), enumerationOptions)
|
||||
static (ref entry) => new FileEntry(entry.ToFullPath(), entry.Length), enumerationOptions)
|
||||
{
|
||||
ShouldIncludePredicate = static (ref FileSystemEntry entry) => !entry.IsDirectory,
|
||||
ShouldRecursePredicate = static (ref FileSystemEntry entry) => !IsLink(ref entry)
|
||||
ShouldIncludePredicate = static (ref entry) => !entry.IsDirectory,
|
||||
ShouldRecursePredicate = static (ref entry) => !IsLink(ref entry)
|
||||
}
|
||||
.GetEnumerator();
|
||||
}
|
||||
|
||||
@@ -74,15 +74,16 @@ public sealed class HashEngine(HashEngineOptions? options = null)
|
||||
ArgumentNullException.ThrowIfNull(algorithms);
|
||||
if (algorithms.Count == 0) throw new ArgumentException("At least one algorithm is required.", nameof(algorithms));
|
||||
|
||||
var functions = new HashFunction[algorithms.Count];
|
||||
// Only the functions created so far are disposed if creating one of them fails.
|
||||
var functions = new List<HashFunction>(algorithms.Count);
|
||||
var current = ArrayPool<byte>.Shared.Rent(bufferSize);
|
||||
var next = ArrayPool<byte>.Shared.Rent(bufferSize);
|
||||
ValueTask<int> pendingRead = default;
|
||||
var readInFlight = false;
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < functions.Length; i++)
|
||||
functions[i] = HashFunction.Create(algorithms[i], _options.Blake3ParallelThreshold);
|
||||
foreach (var algorithm in algorithms)
|
||||
functions.Add(HashFunction.Create(algorithm, _options.Blake3ParallelThreshold));
|
||||
|
||||
pendingRead = stream.ReadAsync(current.AsMemory(0, bufferSize), cancellationToken);
|
||||
readInFlight = true;
|
||||
@@ -101,8 +102,8 @@ public sealed class HashEngine(HashEngineOptions? options = null)
|
||||
(current, next) = (next, current);
|
||||
}
|
||||
|
||||
var results = new HashResult[functions.Length];
|
||||
for (var i = 0; i < functions.Length; i++)
|
||||
var results = new HashResult[functions.Count];
|
||||
for (var i = 0; i < functions.Count; i++)
|
||||
results[i] = new HashResult(algorithms[i], functions[i].GetHash());
|
||||
return results;
|
||||
}
|
||||
@@ -121,20 +122,20 @@ public sealed class HashEngine(HashEngineOptions? options = null)
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var function in functions) function?.Dispose();
|
||||
foreach (var function in functions) function.Dispose();
|
||||
ArrayPool<byte>.Shared.Return(current);
|
||||
ArrayPool<byte>.Shared.Return(next);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Append(HashFunction[] functions, byte[] buffer, int count)
|
||||
private static void Append(List<HashFunction> functions, byte[] buffer, int count)
|
||||
{
|
||||
if (functions.Length == 1)
|
||||
if (functions.Count == 1)
|
||||
{
|
||||
functions[0].Append(buffer.AsSpan(0, count));
|
||||
return;
|
||||
}
|
||||
|
||||
Parallel.For(0, functions.Length, i => functions[i].Append(buffer.AsSpan(0, count)));
|
||||
Parallel.For(0, functions.Count, i => functions[i].Append(buffer.AsSpan(0, count)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user