fix: harden parsing and edge cases found by new analyzers
Enables Meziantou.Analyzer and ReferenceTrimmer for every project (CI builds with -warnaserror) and fixes what they and the new tests found: - Checksum parsing bounds regex work: 1 s match timeout and over-long lines are reported as invalid instead of stalling. - Release notes from the network are converted with timed-out generated regexes; blank lines before lists are no longer swallowed. - --files-from only deletes the app's own temporary list, never an arbitrary file passed on the command line. - Opening the data folder no longer accepts sibling folders that merely share a name prefix. - Search highlighting uses the same culture-aware match length as the filter. - British English is detected for Australia, New Zealand, Ireland and South Africa. - Separate run/stop buttons per row so the tooltip and screen-reader name match the action; JSON/CSV export types are translated. - Settings saves are serialised under a lock; ConfigureAwait in Core. - Version 1.2.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fda1bf2928
commit
c8ccabee57
19 files changed
+181
-42
No files matched your search
@@ -63,3 +63,19 @@ dotnet_naming_symbols.private_fields.applicable_kinds = field
|
||||
dotnet_naming_symbols.private_fields.applicable_accessibilities = private
|
||||
dotnet_naming_style.underscore_camel.capitalization = camel_case
|
||||
dotnet_naming_style.underscore_camel.required_prefix = _
|
||||
|
||||
# Meziantou.Analyzer rules that do not fit this code base.
|
||||
dotnet_diagnostic.MA0006.severity = none # string == is already ordinal
|
||||
dotnet_diagnostic.MA0016.severity = none # concrete collection types in signatures are fine here
|
||||
dotnet_diagnostic.MA0048.severity = none # small related types share a file
|
||||
dotnet_diagnostic.MA0049.severity = none # HashTool.App.App
|
||||
dotnet_diagnostic.MA0051.severity = none # method length
|
||||
|
||||
# UI code, tests and benchmarks resume on the caller's context; async void is how UI event handlers are written.
|
||||
[{src/HashTool.App/**.cs,tests/**.cs,bench/**.cs}]
|
||||
dotnet_diagnostic.MA0004.severity = none
|
||||
dotnet_diagnostic.MA0147.severity = none
|
||||
|
||||
[{tests/**.cs,bench/**.cs}]
|
||||
dotnet_diagnostic.MA0002.severity = none
|
||||
dotnet_diagnostic.MA0009.severity = none
|
||||
+13
-1
@@ -7,7 +7,7 @@
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
|
||||
<!-- Single source of truth for the product version (the release workflow also passes -p:Version=<tag>). -->
|
||||
<Version>1.1.3</Version>
|
||||
<Version>1.2.0</Version>
|
||||
<Authors>poli0981</Authors>
|
||||
<Company>poli0981</Company>
|
||||
<Product>Hash Tool</Product>
|
||||
@@ -23,5 +23,17 @@
|
||||
<NuGetAudit>true</NuGetAudit>
|
||||
<NuGetAuditMode>all</NuGetAuditMode>
|
||||
<NuGetAuditLevel>low</NuGetAuditLevel>
|
||||
|
||||
<!-- ReferenceTrimmer reports package and project references that are never used. -->
|
||||
<ReferenceTrimmerUseSymbolAnalysis>true</ReferenceTrimmerUseSymbolAnalysis>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<!-- Documentation comments are for readers, not a public API: do not demand them for every member or parameter. -->
|
||||
<NoWarn>$(NoWarn);CS1591;CS1573</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Analyzers for every project: unused references and common .NET mistakes (culture, async, comparisons). -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ReferenceTrimmer" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers" />
|
||||
<PackageReference Include="Meziantou.Analyzer" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -17,6 +17,7 @@
|
||||
<ItemGroup Label="Application">
|
||||
<PackageVersion Include="Blake3" Version="3.0.2" />
|
||||
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
|
||||
<PackageVersion Include="System.CommandLine" Version="2.0.13" />
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.13" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.13" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.13" />
|
||||
@@ -24,6 +25,15 @@
|
||||
<PackageVersion Include="Velopack" Version="1.2.161" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Label="Tools">
|
||||
<PackageVersion Include="BenchmarkDotNet" Version="0.15.8" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Label="Analyzers">
|
||||
<PackageVersion Include="Meziantou.Analyzer" Version="3.0.303" />
|
||||
<PackageVersion Include="ReferenceTrimmer" Version="3.5.9" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Label="Tests">
|
||||
<!-- xunit.v3 4.x breaks Avalonia.Headless.XUnit (AvaloniaUI/Avalonia#22072); stay on 3.2.x until it is fixed. -->
|
||||
<PackageVersion Include="xunit.v3.mtp-v2" Version="3.2.2" />
|
||||
|
||||
@@ -57,7 +57,7 @@ public sealed record AppCommandLine(
|
||||
if (Next() is { } list && File.Exists(list))
|
||||
{
|
||||
paths.AddRange(File.ReadAllLines(list).Where(l => !string.IsNullOrWhiteSpace(l)));
|
||||
TryDelete(list);
|
||||
if (IsTemporaryFileList(list)) TryDelete(list);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -79,10 +79,26 @@ public sealed record AppCommandLine(
|
||||
}
|
||||
}
|
||||
|
||||
var resolved = paths.Select(p => Path.GetFullPath(Path.Combine(workingDirectory, p))).Distinct().ToList();
|
||||
var resolved = paths.Select(p => Path.GetFullPath(Path.Combine(workingDirectory, p)))
|
||||
.Distinct(OperatingSystem.IsLinux() ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase).ToList();
|
||||
return new AppCommandLine(verb, resolved, smoke, smokeOutput, expected, waitPid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True only for the list <see cref="Elevation.RestartElevated"/> writes (<c>%TEMP%\hashtool-<guid>.txt</c>), so a
|
||||
/// crafted command line cannot make the app delete any other file.
|
||||
/// </summary>
|
||||
internal static bool IsTemporaryFileList(string path)
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
var name = Path.GetFileNameWithoutExtension(full);
|
||||
return string.Equals(Path.GetDirectoryName(full), Path.GetFullPath(Path.GetTempPath()).TrimEnd(Path.DirectorySeparatorChar),
|
||||
OperatingSystem.IsLinux() ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase) &&
|
||||
Path.GetExtension(full) == ".txt" &&
|
||||
name.StartsWith("hashtool-", StringComparison.Ordinal) &&
|
||||
Guid.TryParseExact(name["hashtool-".Length..], "N", out _);
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Threading;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace HashTool.App.Infrastructure.Logging;
|
||||
@@ -22,6 +23,11 @@ public sealed record LogEntry(DateTimeOffset Timestamp, LogLevel Level, string C
|
||||
$"{Timestamp.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)} [{LevelTag}] {Category}: {Message}";
|
||||
}
|
||||
|
||||
public sealed class LogEntryEventArgs(LogEntry entry) : EventArgs
|
||||
{
|
||||
public LogEntry Entry { get; } = entry;
|
||||
}
|
||||
|
||||
/// <summary>Keeps the most recent log entries in memory for the Developer console.</summary>
|
||||
public sealed class LogSink : ILoggerProvider
|
||||
{
|
||||
@@ -29,12 +35,12 @@ public sealed class LogSink : ILoggerProvider
|
||||
|
||||
private readonly Queue<LogEntry> _entries = new(Capacity);
|
||||
private readonly PathSanitizer _sanitizer;
|
||||
private readonly object _gate = new();
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
public LogSink(PathSanitizer sanitizer) => _sanitizer = sanitizer;
|
||||
|
||||
/// <summary>Raised on the logging thread for every entry.</summary>
|
||||
public event EventHandler<LogEntry>? EntryAdded;
|
||||
public event EventHandler<LogEntryEventArgs>? EntryAdded;
|
||||
|
||||
/// <summary>When false, entries are not recorded (the console's pause button).</summary>
|
||||
public bool IsRecording { get; set; } = true;
|
||||
@@ -66,7 +72,7 @@ public sealed class LogSink : ILoggerProvider
|
||||
_entries.Enqueue(entry);
|
||||
}
|
||||
|
||||
EntryAdded?.Invoke(this, entry);
|
||||
EntryAdded?.Invoke(this, new LogEntryEventArgs(entry));
|
||||
}
|
||||
|
||||
private sealed class SinkLogger(LogSink sink, string category) : ILogger
|
||||
|
||||
@@ -37,7 +37,7 @@ public static class SmokeTest
|
||||
AppBuilder.Configure<App>().UseHeadless(new AvaloniaHeadlessPlatformOptions()).WithInterFont().SetupWithoutStarting();
|
||||
using var done = new CancellationTokenSource();
|
||||
var checks = RunChecksAsync(commandLine, report);
|
||||
checks.ContinueWith(_ => done.Cancel(), TaskScheduler.Default);
|
||||
_ = checks.ContinueWith(_ => done.Cancel(), TaskScheduler.Default);
|
||||
Dispatcher.UIThread.MainLoop(done.Token);
|
||||
checks.GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
@@ -199,6 +199,11 @@ public sealed partial class LocalizationService : ObservableObject
|
||||
codes.Contains("es-419", StringComparer.OrdinalIgnoreCase))
|
||||
return "es-419";
|
||||
|
||||
// Commonwealth English uses British spelling.
|
||||
if (language == "en" && name.Split('-')[^1].ToUpperInvariant() is "AU" or "NZ" or "IE" or "ZA" or "MT" or "CY" &&
|
||||
codes.Contains("en-GB", StringComparer.OrdinalIgnoreCase))
|
||||
return "en-GB";
|
||||
|
||||
// 3. Same language, preferred variant first, then any variant whose language subtag matches exactly.
|
||||
if (PreferredVariants.TryGetValue(language, out var preferred) && codes.Contains(preferred, StringComparer.OrdinalIgnoreCase))
|
||||
return preferred;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Avalonia.Media;
|
||||
using HashTool.Core.Configuration;
|
||||
@@ -57,7 +58,7 @@ public static class ThemePalettes
|
||||
string? success = null, string? error = null, string? warning = null, string? info = null, string? muted = null,
|
||||
string? secondary = null)
|
||||
{
|
||||
var p = new Dictionary<string, object>
|
||||
var p = new Dictionary<string, object>(StringComparer.Ordinal)
|
||||
{
|
||||
["AppBackgroundBrush"] = Brush.Parse(background),
|
||||
["PaneBackgroundBrush"] = Brush.Parse(pane),
|
||||
|
||||
@@ -154,8 +154,8 @@ public sealed class LauncherService(MainWindowAccessor main, ILogger<LauncherSer
|
||||
{
|
||||
// Only folders inside the app's data directory are opened (logs, settings).
|
||||
var full = Path.GetFullPath(path);
|
||||
var root = Path.GetFullPath(AppPaths.DataDirectory);
|
||||
if (!full.StartsWith(root, StringComparison.OrdinalIgnoreCase) || !Directory.Exists(full))
|
||||
var relative = Path.GetRelativePath(Path.GetFullPath(AppPaths.DataDirectory), full);
|
||||
if (relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) || !Directory.Exists(full))
|
||||
{
|
||||
logger.LogWarning("Refused to open folder {Path}", path);
|
||||
return;
|
||||
|
||||
@@ -99,8 +99,8 @@ public sealed partial class CreateHashViewModel : FileListViewModelBase
|
||||
new(L["FileType_Bsd"], "*.txt", ExportFormat.Bsd)
|
||||
};
|
||||
if (single == HashType.CRC32) types.Add(new FileTypeChoice(L["FileType_Sfv"], "*.sfv", ExportFormat.Sfv));
|
||||
types.Add(new FileTypeChoice("JSON", "*.json", ExportFormat.Json));
|
||||
types.Add(new FileTypeChoice("CSV", "*.csv", ExportFormat.Csv));
|
||||
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];
|
||||
types.Remove(preferred);
|
||||
|
||||
@@ -41,7 +41,7 @@ public sealed partial class DeveloperViewModel : ObservableObject
|
||||
localization.LanguageChanged += (_, _) => Localization = new LocalizationProxy(localization);
|
||||
|
||||
Entries.AddRange(sink.Snapshot());
|
||||
sink.EntryAdded += (_, entry) => _incoming.Enqueue(entry);
|
||||
sink.EntryAdded += (_, e) => _incoming.Enqueue(e.Entry);
|
||||
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Flush());
|
||||
_timer.Start();
|
||||
}
|
||||
|
||||
@@ -521,7 +521,7 @@ public abstract partial class FileListViewModelBase : ObservableObject, IHashJob
|
||||
{
|
||||
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 (Elevation.RestartElevated(ElevationVerb, _all.Select(i => SourcePathForRestart(i)).Distinct().ToList()))
|
||||
if (Elevation.RestartElevated(ElevationVerb, _all.Select(i => SourcePathForRestart(i)).Distinct(_byPath.Comparer).ToList()))
|
||||
RequestShutdown?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
|
||||
@@ -218,13 +218,40 @@ public sealed partial class UpdateViewModel : ObservableObject
|
||||
internal static string? ToPlainText(string? markdown)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(markdown)) return null;
|
||||
var text = markdown.Replace("\r\n", "\n");
|
||||
text = Regex.Replace(text, @"^#{1,6}\s*", "", RegexOptions.Multiline);
|
||||
text = Regex.Replace(text, @"^\s*[-*+]\s+", "• ", RegexOptions.Multiline);
|
||||
text = Regex.Replace(text, @"\*\*(.+?)\*\*|__(.+?)__", "$1$2");
|
||||
text = Regex.Replace(text, @"`([^`]+)`", "$1");
|
||||
text = Regex.Replace(text, @"\[([^\]]+)\]\([^)]+\)", "$1");
|
||||
text = Regex.Replace(text, @"\n{3,}", "\n\n");
|
||||
var text = markdown.Replace("\r\n", "\n", StringComparison.Ordinal);
|
||||
try
|
||||
{
|
||||
text = Heading().Replace(text, "");
|
||||
text = Bullet().Replace(text, "• ");
|
||||
text = Bold().Replace(text, "${a}${b}");
|
||||
text = Code().Replace(text, "${code}");
|
||||
text = Link().Replace(text, "${text}");
|
||||
text = BlankLines().Replace(text, "\n\n");
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
// Notes come from the network; show them unformatted rather than hang on a pathological input.
|
||||
}
|
||||
|
||||
return text.Trim();
|
||||
}
|
||||
|
||||
// [ \t] rather than \s: \s also matches line breaks, which swallowed the blank line before a list.
|
||||
[GeneratedRegex(@"^#{1,6}[ \t]*", RegexOptions.Multiline, 1000)]
|
||||
private static partial Regex Heading();
|
||||
|
||||
[GeneratedRegex(@"^[ \t]*[-*+][ \t]+", RegexOptions.Multiline, 1000)]
|
||||
private static partial Regex Bullet();
|
||||
|
||||
[GeneratedRegex(@"\*\*(?<a>.+?)\*\*|__(?<b>.+?)__", RegexOptions.ExplicitCapture, 1000)]
|
||||
private static partial Regex Bold();
|
||||
|
||||
[GeneratedRegex(@"`(?<code>[^`]+)`", RegexOptions.ExplicitCapture, 1000)]
|
||||
private static partial Regex Code();
|
||||
|
||||
[GeneratedRegex(@"\[(?<text>[^\]]+)\]\([^)]+\)", RegexOptions.ExplicitCapture, 1000)]
|
||||
private static partial Regex Link();
|
||||
|
||||
[GeneratedRegex(@"\n{3,}", RegexOptions.None, 1000)]
|
||||
private static partial Regex BlankLines();
|
||||
}
|
||||
@@ -174,13 +174,16 @@
|
||||
|
||||
<StackPanel Grid.Column="4" Orientation="Horizontal" Spacing="2" VerticalAlignment="Center">
|
||||
<Button Classes="icon" Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).RunItemCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
CommandParameter="{Binding}" IsVisible="{Binding !IsProcessing}"
|
||||
ToolTip.Tip="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_Verify]}"
|
||||
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_Verify]}">
|
||||
<Panel>
|
||||
<icons:MaterialIcon Kind="PlayCircleOutline" Width="18" Height="18" Foreground="{DynamicResource StatusSuccessBrush}" IsVisible="{Binding !IsProcessing}" />
|
||||
<icons:MaterialIcon Kind="StopCircleOutline" Width="18" Height="18" Foreground="{DynamicResource StatusWarningBrush}" IsVisible="{Binding IsProcessing}" />
|
||||
</Panel>
|
||||
<icons:MaterialIcon Kind="PlayCircleOutline" Width="18" Height="18" Foreground="{DynamicResource StatusSuccessBrush}" />
|
||||
</Button>
|
||||
<Button Classes="icon" Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).RunItemCommand}"
|
||||
CommandParameter="{Binding}" IsVisible="{Binding IsProcessing}"
|
||||
ToolTip.Tip="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_Stop]}"
|
||||
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).Localization[Tip_Stop]}">
|
||||
<icons:MaterialIcon Kind="StopCircleOutline" Width="18" Height="18" Foreground="{DynamicResource StatusWarningBrush}" />
|
||||
</Button>
|
||||
<Button Classes="icon" Command="{Binding $parent[ListBox].((vm:CheckHashViewModel)DataContext).ClearItemResultCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
|
||||
@@ -190,13 +190,16 @@
|
||||
<icons:MaterialIcon Kind="ContentSave" Width="18" Height="18" />
|
||||
</Button>
|
||||
<Button Classes="icon" Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).RunItemCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
CommandParameter="{Binding}" IsVisible="{Binding !IsProcessing}"
|
||||
ToolTip.Tip="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_Compute]}"
|
||||
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_Compute]}">
|
||||
<Panel>
|
||||
<icons:MaterialIcon Kind="PlayCircleOutline" Width="18" Height="18" Foreground="{DynamicResource StatusSuccessBrush}" IsVisible="{Binding !IsProcessing}" />
|
||||
<icons:MaterialIcon Kind="StopCircleOutline" Width="18" Height="18" Foreground="{DynamicResource StatusWarningBrush}" IsVisible="{Binding IsProcessing}" />
|
||||
</Panel>
|
||||
<icons:MaterialIcon Kind="PlayCircleOutline" Width="18" Height="18" Foreground="{DynamicResource StatusSuccessBrush}" />
|
||||
</Button>
|
||||
<Button Classes="icon" Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).RunItemCommand}"
|
||||
CommandParameter="{Binding}" IsVisible="{Binding IsProcessing}"
|
||||
ToolTip.Tip="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_Stop]}"
|
||||
AutomationProperties.Name="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).Localization[Tip_Stop]}">
|
||||
<icons:MaterialIcon Kind="StopCircleOutline" Width="18" Height="18" Foreground="{DynamicResource StatusWarningBrush}" />
|
||||
</Button>
|
||||
<Button Classes="icon" Command="{Binding $parent[ListBox].((vm:CreateHashViewModel)DataContext).ClearItemResultCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
|
||||
@@ -18,19 +18,24 @@ public static partial class ChecksumParser
|
||||
/// <summary>Larger files are rejected instead of being read into memory.</summary>
|
||||
public const long MaxFileSize = 16L * ByteSize.OneMB;
|
||||
|
||||
[GeneratedRegex(@"^(?<tag>[A-Za-z][A-Za-z0-9_\-]*)\s?\((?<name>.*)\)\s?=\s?(?<hash>[0-9A-Fa-f]+)$", RegexOptions.CultureInvariant)]
|
||||
/// <summary>Longer lines cannot hold a real path and are reported as invalid without running the patterns.</summary>
|
||||
private const int MaxLineLength = 32 * 1024;
|
||||
|
||||
private const int MatchTimeoutMilliseconds = 1000;
|
||||
|
||||
[GeneratedRegex(@"^(?<tag>[A-Za-z][A-Za-z0-9_\-]*)\s?\((?<name>.*)\)\s?=\s?(?<hash>[0-9A-Fa-f]+)$", RegexOptions.CultureInvariant, MatchTimeoutMilliseconds)]
|
||||
private static partial Regex BsdLine();
|
||||
|
||||
[GeneratedRegex(@"^(?<escaped>\\)?(?<xxh3>XXH3_)?(?<hash>[0-9A-Fa-f]{8,128})(?: \*| {1,2})(?<name>\S.*)$", RegexOptions.CultureInvariant)]
|
||||
[GeneratedRegex(@"^(?<escaped>\\)?(?<xxh3>XXH3_)?(?<hash>[0-9A-Fa-f]{8,128})(?: \*| {1,2})(?<name>\S.*)$", RegexOptions.CultureInvariant, MatchTimeoutMilliseconds)]
|
||||
private static partial Regex GnuLine();
|
||||
|
||||
[GeneratedRegex(@"^(?<name>.+?)\s+(?<hash>[0-9A-Fa-f]{8})$", RegexOptions.CultureInvariant)]
|
||||
[GeneratedRegex(@"^(?<name>.+?)\s+(?<hash>[0-9A-Fa-f]{8})$", RegexOptions.CultureInvariant, MatchTimeoutMilliseconds)]
|
||||
private static partial Regex SfvLine();
|
||||
|
||||
[GeneratedRegex(@"^(?:XXH3_)?[0-9A-Fa-f]{2}(?:\s?[0-9A-Fa-f]{2}){3,63}$", RegexOptions.CultureInvariant)]
|
||||
[GeneratedRegex(@"^(?:XXH3_)?[0-9A-Fa-f]{2}(?:\s?[0-9A-Fa-f]{2}){3,63}$", RegexOptions.CultureInvariant, MatchTimeoutMilliseconds)]
|
||||
private static partial Regex BareLine();
|
||||
|
||||
[GeneratedRegex(@"^(?:[A-Za-z0-9\-]+ hash of .*:|CertUtil: .*)$", RegexOptions.CultureInvariant)]
|
||||
[GeneratedRegex(@"^(?:[A-Za-z0-9\-]+ hash of .*:|CertUtil: .*)$", RegexOptions.CultureInvariant, MatchTimeoutMilliseconds)]
|
||||
private static partial Regex CertUtilNoise();
|
||||
|
||||
/// <summary>Reads and parses a checksum file.</summary>
|
||||
@@ -69,9 +74,15 @@ public static partial class ChecksumParser
|
||||
var line = rawLine.TrimEnd('\r').ToString();
|
||||
if (lineNumber == 1) line = line.TrimStart('');
|
||||
var trimmed = line.Trim();
|
||||
if (trimmed.Length == 0 || trimmed[0] is '#' or ';' || CertUtilNoise().IsMatch(trimmed)) continue;
|
||||
if (trimmed.Length == 0 || trimmed[0] is '#' or ';') continue;
|
||||
if (trimmed.Length > MaxLineLength)
|
||||
{
|
||||
invalid.Add(lineNumber);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryParseLine(line, trimmed, fileNameHint, userHint, lineNumber, out var entry, out var lineFormat))
|
||||
if (IsNoise(trimmed)) continue;
|
||||
if (TryParseLineSafely(line, trimmed, fileNameHint, userHint, lineNumber, out var entry, out var lineFormat))
|
||||
{
|
||||
entries.Add(entry);
|
||||
format ??= lineFormat;
|
||||
@@ -85,6 +96,34 @@ public static partial class ChecksumParser
|
||||
return new ChecksumDocument(entries, invalid, format ?? ChecksumFormat.Gnu);
|
||||
}
|
||||
|
||||
private static bool IsNoise(string trimmed)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CertUtilNoise().IsMatch(trimmed);
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A line that makes a pattern time out is reported as invalid instead of failing the whole file.</summary>
|
||||
private static bool TryParseLineSafely(string line, string trimmed, HashType? fileNameHint, HashType? userHint, int lineNumber,
|
||||
out ChecksumEntry entry, out ChecksumFormat format)
|
||||
{
|
||||
try
|
||||
{
|
||||
return TryParseLine(line, trimmed, fileNameHint, userHint, lineNumber, out entry, out format);
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
entry = null!;
|
||||
format = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryParseLine(string line, string trimmed, HashType? fileNameHint, HashType? userHint, int lineNumber,
|
||||
out ChecksumEntry entry, out ChecksumFormat format)
|
||||
{
|
||||
|
||||
@@ -65,7 +65,7 @@ public static class FileEnumerator
|
||||
RecurseSubdirectories = true,
|
||||
IgnoreInaccessible = true,
|
||||
ReturnSpecialDirectories = false,
|
||||
AttributesToSkip = options.IncludeHidden ? 0 : FileAttributes.Hidden | FileAttributes.System
|
||||
AttributesToSkip = options.IncludeHidden ? default : FileAttributes.Hidden | FileAttributes.System
|
||||
};
|
||||
|
||||
IEnumerator<FileEntry> enumerator;
|
||||
@@ -113,7 +113,7 @@ public static class FileEnumerator
|
||||
/// </summary>
|
||||
private static bool IsLink(ref FileSystemEntry entry)
|
||||
{
|
||||
if ((entry.Attributes & FileAttributes.ReparsePoint) == 0) return false;
|
||||
if (!entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) return false;
|
||||
try
|
||||
{
|
||||
return new DirectoryInfo(entry.ToFullPath()).LinkTarget is not null;
|
||||
|
||||
@@ -49,7 +49,7 @@ public sealed class HashEngine(HashEngineOptions? options = null)
|
||||
|
||||
// Allow other processes to keep the file open for writing or deletion: refusing to hash a file just because a
|
||||
// downloader or editor still has a handle produced most of the "file in use" errors in 1.x.
|
||||
await using var stream = new FileStream(path, new FileStreamOptions
|
||||
var stream = new FileStream(path, new FileStreamOptions
|
||||
{
|
||||
Mode = FileMode.Open,
|
||||
Access = FileAccess.Read,
|
||||
@@ -57,6 +57,7 @@ public sealed class HashEngine(HashEngineOptions? options = null)
|
||||
BufferSize = 0,
|
||||
Options = FileOptions.Asynchronous | FileOptions.SequentialScan
|
||||
});
|
||||
await using var disposeStream = stream.ConfigureAwait(false);
|
||||
|
||||
var bufferSize = stream.Length >= _options.LargeFileThreshold ? _options.LargeFileBufferSize : _options.BufferSize;
|
||||
return await ComputeStreamAsync(stream, algorithms, bufferSize, onBytesRead, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -52,7 +52,7 @@ internal abstract class HashFunction : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Crc32.GetCurrentHash()"/> emits little-endian bytes; every checksum tool (7-Zip, SFV, cksum -a crc32b)
|
||||
/// <c>Crc32.GetCurrentHash()</c> emits little-endian bytes; every checksum tool (7-Zip, SFV, cksum -a crc32b)
|
||||
/// prints the CRC as a big-endian number, so convert it.
|
||||
/// </summary>
|
||||
private sealed class Crc32HashFunction : HashFunction
|
||||
|
||||
Reference in new issue
Block a user