feat: hashtool CLI, app tests, release packaging inputs and benchmarks
- src/HashTool.Cli: `hashtool hash | verify | check | algorithms` on top of Core, NativeAOT-ready (3.9 MB native binary), coreutils-style output and exit codes (0 ok, 1 failed/mismatch, 2 usage or unreadable checksum file); Windows paths are written with '/' so lines need no escaping. - tests/HashTool.Cli.Tests: commands, formats and exit codes. - tests/HashTool.App.Tests (Avalonia headless): every page in several languages including RTL, a folder create-and-verify flow, translation integrity (keys, placeholders, Languages.json/resx/project wiring, satellite assemblies, unused keys), system language detection, command line parsing and helpers. - tests/Compat/LegacyClient: drives Velopack 0.0.1298 (the library inside Hash Tool 1.1.x) against new release files for the upgrade gate. - build/macos/Info.plist keeps the 1.x bundle identity and adds "Open With" document types; build/linux/hashtool.png is the AppImage icon. - bench/HashTool.Benchmarks (BenchmarkDotNet) and a tool manifest pinning vpk 1.2.161, nuget-license and CycloneDX. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c8ccabee57
commit
4bd17a50f4
22 files changed
+1538
No files matched your search
@@ -1,9 +1,15 @@
|
||||
<Solution>
|
||||
<Folder Name="/bench/">
|
||||
<Project Path="bench/HashTool.Benchmarks/HashTool.Benchmarks.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/HashTool.App/HashTool.App.csproj" />
|
||||
<Project Path="src/HashTool.Cli/HashTool.Cli.csproj" />
|
||||
<Project Path="src/HashTool.Core/HashTool.Core.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/HashTool.App.Tests/HashTool.App.Tests.csproj" />
|
||||
<Project Path="tests/HashTool.Cli.Tests/HashTool.Cli.Tests.csproj" />
|
||||
<Project Path="tests/HashTool.Core.Tests/HashTool.Core.Tests.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
<!-- Run manually, see docs/ARCHITECTURE.md (Benchmarks). -->
|
||||
<Optimize>true</Optimize>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BenchmarkDotNet" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\HashTool.Core\HashTool.Core.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,128 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BenchmarkDotNet.Attributes;
|
||||
using HashTool.Core;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Processing;
|
||||
|
||||
namespace HashTool.Benchmarks;
|
||||
|
||||
/// <summary>Large-file throughput of <see cref="HashEngine"/> against the one-line BCL approach.</summary>
|
||||
[MemoryDiagnoser]
|
||||
public class LargeFileBenchmarks
|
||||
{
|
||||
private readonly HashEngine _engine = new();
|
||||
private string _file = null!;
|
||||
|
||||
[Params(256)]
|
||||
public int SizeMB { get; set; }
|
||||
|
||||
[GlobalSetup]
|
||||
public void Setup() => _file = TestFiles.Create($"large-{SizeMB}", (long)SizeMB * ByteSize.OneMB);
|
||||
|
||||
[GlobalCleanup]
|
||||
public void Cleanup() => File.Delete(_file);
|
||||
|
||||
[Benchmark(Baseline = true, Description = "SHA256.HashData(FileStream)")]
|
||||
public byte[] Bcl_Sha256()
|
||||
{
|
||||
using var stream = File.OpenRead(_file);
|
||||
return SHA256.HashData(stream);
|
||||
}
|
||||
|
||||
[Benchmark]
|
||||
public Task<HashResult> Sha256() => _engine.ComputeFileAsync(_file, HashType.SHA256);
|
||||
|
||||
[Benchmark]
|
||||
public Task<HashResult> Blake3() => _engine.ComputeFileAsync(_file, HashType.BLAKE3);
|
||||
|
||||
[Benchmark]
|
||||
public Task<HashResult> XxHash3() => _engine.ComputeFileAsync(_file, HashType.XxHash3);
|
||||
|
||||
[Benchmark]
|
||||
public Task<HashResult> Crc32() => _engine.ComputeFileAsync(_file, HashType.CRC32);
|
||||
|
||||
/// <summary>One read of the file for three algorithms (1.x read the file once per algorithm).</summary>
|
||||
[Benchmark]
|
||||
public Task<HashResult[]> Sha256_Md5_Crc32_OnePass() => _engine.ComputeFileAsync(_file, [HashType.SHA256, HashType.MD5, HashType.CRC32]);
|
||||
}
|
||||
|
||||
/// <summary>Many small files: sequential hashing against <see cref="BatchProcessor"/>.</summary>
|
||||
[MemoryDiagnoser]
|
||||
public class SmallFilesBenchmarks
|
||||
{
|
||||
private readonly HashEngine _engine = new();
|
||||
private string _directory = null!;
|
||||
private List<string> _files = null!;
|
||||
|
||||
[Params(2000)]
|
||||
public int Count { get; set; }
|
||||
|
||||
[GlobalSetup]
|
||||
public void Setup()
|
||||
{
|
||||
_directory = Directory.CreateTempSubdirectory("hashtool-bench-small-").FullName;
|
||||
_files = [];
|
||||
var buffer = new byte[16 * ByteSize.OneKB];
|
||||
for (var i = 0; i < Count; i++)
|
||||
{
|
||||
Random.Shared.NextBytes(buffer);
|
||||
var path = Path.Combine(_directory, $"{i:D5}.bin");
|
||||
File.WriteAllBytes(path, buffer);
|
||||
_files.Add(path);
|
||||
}
|
||||
}
|
||||
|
||||
[GlobalCleanup]
|
||||
public void Cleanup() => Directory.Delete(_directory, recursive: true);
|
||||
|
||||
[Benchmark(Baseline = true)]
|
||||
public async Task Sequential()
|
||||
{
|
||||
foreach (var file in _files) await _engine.ComputeFileAsync(file, HashType.SHA256);
|
||||
}
|
||||
|
||||
[Benchmark]
|
||||
public Task Batch() => new BatchProcessor(_engine).RunAsync(_files,
|
||||
f => new HashJob(f, 16 * ByteSize.OneKB, [HashType.SHA256]), NullObserver.Instance, CancellationToken.None);
|
||||
|
||||
private sealed class NullObserver : IHashJobObserver<string>
|
||||
{
|
||||
public static readonly NullObserver Instance = new();
|
||||
|
||||
public void OnStarted(string item)
|
||||
{
|
||||
}
|
||||
|
||||
public void OnProgress(string item, long bytesRead)
|
||||
{
|
||||
}
|
||||
|
||||
public void OnCompleted(string item, HashJobResult result)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class TestFiles
|
||||
{
|
||||
public static string Create(string name, long size)
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"hashtool-bench-{name}.bin");
|
||||
if (File.Exists(path) && new FileInfo(path).Length == size) return path;
|
||||
|
||||
using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 0);
|
||||
var buffer = new byte[4 * ByteSize.OneMB];
|
||||
for (long written = 0; written < size; written += buffer.Length)
|
||||
{
|
||||
Random.Shared.NextBytes(buffer);
|
||||
stream.Write(buffer, 0, (int)Math.Min(buffer.Length, size - written));
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using BenchmarkDotNet.Running;
|
||||
|
||||
namespace HashTool.Benchmarks;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
@@ -0,0 +1,86 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<!--
|
||||
Info.plist of the macOS app bundle. The release workflow replaces @VERSION@ and hands the file to vpk (plist option).
|
||||
Velopack copies a custom plist verbatim, so every key it would otherwise generate is listed here. CFBundleIdentifier,
|
||||
CFBundleName and CFBundleExecutable must never change: they are what Hash Tool 1.1.x installed (Velopack's defaults).
|
||||
-->
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleName</key>
|
||||
<string>Hash Tool</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Hash Tool</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.HashTool.HashTool</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>@VERSION@</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>@VERSION@</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>CheckHash</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>icons.icns</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<true />
|
||||
<key>LSApplicationCategoryType</key>
|
||||
<string>public.app-category.utilities</string>
|
||||
<!-- "Open With > Hash Tool": checksum files open on the Verify page, anything else on the Generate page. -->
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>Checksum File</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Viewer</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Alternate</string>
|
||||
<key>CFBundleTypeExtensions</key>
|
||||
<array>
|
||||
<string>md5</string>
|
||||
<string>md5sum</string>
|
||||
<string>sha1</string>
|
||||
<string>sha1sum</string>
|
||||
<string>sha256</string>
|
||||
<string>sha256sum</string>
|
||||
<string>sha384</string>
|
||||
<string>sha384sum</string>
|
||||
<string>sha512</string>
|
||||
<string>sha512sum</string>
|
||||
<string>blake3</string>
|
||||
<string>b3</string>
|
||||
<string>b3sum</string>
|
||||
<string>xxhash32</string>
|
||||
<string>xxh32</string>
|
||||
<string>xxhash64</string>
|
||||
<string>xxh64</string>
|
||||
<string>xxhash3</string>
|
||||
<string>xxh3</string>
|
||||
<string>xxhash128</string>
|
||||
<string>xxh128</string>
|
||||
<string>crc32</string>
|
||||
<string>sfv</string>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>File or Folder</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Viewer</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>None</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array>
|
||||
<string>public.data</string>
|
||||
<string>public.folder</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"vpk": {
|
||||
"version": "1.2.161",
|
||||
"commands": [
|
||||
"vpk"
|
||||
],
|
||||
"rollForward": false
|
||||
},
|
||||
"nuget-license": {
|
||||
"version": "4.0.18",
|
||||
"commands": [
|
||||
"nuget-license"
|
||||
],
|
||||
"rollForward": false
|
||||
},
|
||||
"cyclonedx": {
|
||||
"version": "6.3.1",
|
||||
"commands": [
|
||||
"dotnet-CycloneDX"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.CommandLine;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Files;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Processing;
|
||||
|
||||
namespace HashTool.Cli;
|
||||
|
||||
/// <summary><c>hashtool hash</c>: prints or writes checksum lines for files and folders.</summary>
|
||||
internal static class HashCommand
|
||||
{
|
||||
private sealed record Input(string FullPath, string Display);
|
||||
|
||||
public static Command Create(TextWriter output, TextWriter error)
|
||||
{
|
||||
var paths = new Argument<string[]>("paths") { Description = "Files to hash (folders need --recursive).", Arity = ArgumentArity.OneOrMore };
|
||||
var algorithms = HashToolCommand.AlgorithmOption("Algorithm(s) to use: sha256 (default), sha1, md5, sha384, sha512, blake3, xxhash3, ...");
|
||||
var recursive = new Option<bool>("--recursive", "-r") { Description = "Hash every file inside the given folders." };
|
||||
var hidden = new Option<bool>("--hidden") { Description = "Include hidden and system files when walking folders." };
|
||||
var format = new Option<ExportFormat?>("--format", "-f")
|
||||
{
|
||||
Description = "Output format: gnu (sha256sum style, default for one algorithm), bsd (tagged, default for several), sfv (CRC32 only), json or csv."
|
||||
};
|
||||
var outputFile = new Option<FileInfo?>("--output", "-o")
|
||||
{ Description = "Write to this file instead of the console. Paths inside are relative to its folder.", HelpName = "file" };
|
||||
var upper = new Option<bool>("--uppercase", "-u") { Description = "Print hexadecimal digits in upper case." };
|
||||
var jobs = new Option<int>("--jobs", "-j") { Description = "Files hashed in parallel (0 = automatic, 1 = one at a time for hard disks).", HelpName = "count" };
|
||||
|
||||
var command = new Command("hash", "Compute hashes of files and print them as checksum lines.")
|
||||
{
|
||||
paths, algorithms, recursive, hidden, format, outputFile, upper, jobs
|
||||
};
|
||||
command.SetAction((result, cancellationToken) => RunAsync(new Request(
|
||||
result.GetRequiredValue(paths),
|
||||
result.GetValue(algorithms) is { Length: > 0 } chosen ? chosen : [HashType.SHA256],
|
||||
result.GetValue(recursive),
|
||||
result.GetValue(hidden),
|
||||
result.GetValue(format),
|
||||
result.GetValue(outputFile),
|
||||
result.GetValue(upper) ? HexCase.Upper : HexCase.Lower,
|
||||
result.GetValue(jobs)), output, error, cancellationToken));
|
||||
return command;
|
||||
}
|
||||
|
||||
internal sealed record Request(
|
||||
IReadOnlyList<string> Paths,
|
||||
IReadOnlyList<HashType> Algorithms,
|
||||
bool Recursive,
|
||||
bool IncludeHidden,
|
||||
ExportFormat? Format,
|
||||
FileInfo? OutputFile,
|
||||
HexCase LetterCase,
|
||||
int Jobs);
|
||||
|
||||
internal static async Task<int> RunAsync(Request request, TextWriter output, TextWriter error, CancellationToken cancellationToken)
|
||||
{
|
||||
var format = request.Format ?? (request.Algorithms.Count == 1 ? ExportFormat.Gnu : ExportFormat.Bsd);
|
||||
if (format == ExportFormat.Gnu && request.Algorithms.Count > 1)
|
||||
{
|
||||
error.WriteLine("hashtool: the gnu format holds a single algorithm; use --format bsd, json or csv for several.");
|
||||
return HashToolCommand.UsageError;
|
||||
}
|
||||
|
||||
if (format == ExportFormat.Sfv && request.Algorithms.Any(a => a != HashType.CRC32))
|
||||
{
|
||||
error.WriteLine("hashtool: sfv files contain CRC32 only; add -a crc32.");
|
||||
return HashToolCommand.UsageError;
|
||||
}
|
||||
|
||||
var failures = 0;
|
||||
var relativeTo = request.OutputFile?.DirectoryName;
|
||||
var inputs = Expand(request, relativeTo, error, ref failures, cancellationToken);
|
||||
|
||||
var engine = new HashEngine();
|
||||
var results = new HashResult[]?[inputs.Count];
|
||||
var errors = new Exception?[inputs.Count];
|
||||
var parallelism = request.Jobs > 0 ? request.Jobs : new BatchOptions().EffectiveParallelism;
|
||||
await Parallel.ForEachAsync(Enumerable.Range(0, inputs.Count),
|
||||
new ParallelOptions { MaxDegreeOfParallelism = parallelism, CancellationToken = cancellationToken },
|
||||
async (i, token) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
results[i] = await engine.ComputeFileAsync(inputs[i].FullPath, request.Algorithms, null, token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
errors[i] = ex;
|
||||
}
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
var lines = new List<ChecksumLine>();
|
||||
for (var i = 0; i < inputs.Count; i++)
|
||||
{
|
||||
if (errors[i] is { } ex)
|
||||
{
|
||||
HashToolCommand.ReportError(error, inputs[i].Display, ex);
|
||||
failures++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var size = SafeLength(inputs[i].FullPath);
|
||||
lines.AddRange(results[i]!.Select(r => new ChecksumLine(inputs[i].Display, r.Algorithm, r.ToHex(request.LetterCase), size)));
|
||||
}
|
||||
|
||||
if (request.OutputFile is { } file)
|
||||
{
|
||||
try
|
||||
{
|
||||
await File.WriteAllTextAsync(file.FullName, ChecksumWriter.Write(lines, format, request.LetterCase), new UTF8Encoding(false),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
HashToolCommand.ReportError(error, file.FullName, ex);
|
||||
return HashToolCommand.Failure;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ChecksumWriter.Write(output, lines, format, request.LetterCase);
|
||||
}
|
||||
|
||||
return failures == 0 ? HashToolCommand.Success : HashToolCommand.Failure;
|
||||
}
|
||||
|
||||
private static List<Input> Expand(Request request, string? relativeTo, TextWriter error, ref int failures, CancellationToken cancellationToken)
|
||||
{
|
||||
var inputs = new List<Input>();
|
||||
var seen = new HashSet<string>(OperatingSystem.IsLinux() ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
|
||||
var options = new FileEnumerationOptions { IncludeHidden = request.IncludeHidden };
|
||||
var errors = 0;
|
||||
foreach (var path in request.Paths)
|
||||
{
|
||||
// Relative input stays relative in the output, like sha256sum; with --output it is relative to that file.
|
||||
var displayBase = relativeTo ?? (Path.IsPathRooted(path) ? null : Environment.CurrentDirectory);
|
||||
if (Directory.Exists(path))
|
||||
{
|
||||
if (!request.Recursive)
|
||||
{
|
||||
error.WriteLine($"hashtool: {path}: is a directory (use --recursive to hash the files inside)");
|
||||
errors++;
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var entry in FileEnumerator.EnumerateDirectory(path, options, (p, ex) =>
|
||||
{
|
||||
HashToolCommand.ReportError(error, p, ex);
|
||||
errors++;
|
||||
}, cancellationToken))
|
||||
{
|
||||
if (seen.Add(entry.FullPath)) inputs.Add(new Input(entry.FullPath, HashToolCommand.DisplayPath(entry.FullPath, displayBase)));
|
||||
}
|
||||
}
|
||||
else if (File.Exists(path))
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
if (seen.Add(full)) inputs.Add(new Input(full, relativeTo is null ? HashToolCommand.Portable(path) : HashToolCommand.DisplayPath(full, relativeTo)));
|
||||
}
|
||||
else
|
||||
{
|
||||
error.WriteLine($"hashtool: {path}: No such file or directory");
|
||||
errors++;
|
||||
}
|
||||
}
|
||||
|
||||
failures += errors;
|
||||
return inputs;
|
||||
}
|
||||
|
||||
private static long? SafeLength(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new FileInfo(path).Length;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<RootNamespace>HashTool.Cli</RootNamespace>
|
||||
<AssemblyName>hashtool</AssemblyName>
|
||||
<AssemblyTitle>Hash Tool CLI</AssemblyTitle>
|
||||
<Description>Command-line companion of Hash Tool: compute and verify file hashes and checksum files.</Description>
|
||||
<!-- Published as a single native executable per platform. -->
|
||||
<PublishAot>true</PublishAot>
|
||||
<IsAotCompatible>true</IsAotCompatible>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<!-- Messages are English only; do not ship System.CommandLine's satellite assemblies. -->
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.CommandLine" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\HashTool.Core\HashTool.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="HashTool.Cli.Tests" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,114 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.CommandLine;
|
||||
using System.CommandLine.Parsing;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Hashing;
|
||||
|
||||
namespace HashTool.Cli;
|
||||
|
||||
/// <summary>
|
||||
/// <c>hashtool</c>: compute and verify hashes from the command line. Exit codes follow coreutils' <c>sha256sum</c>:
|
||||
/// 0 = success, 1 = a file failed or did not match, 2 = usage error or unreadable checksum file.
|
||||
/// </summary>
|
||||
public static class HashToolCommand
|
||||
{
|
||||
public const int Success = 0;
|
||||
public const int Failure = 1;
|
||||
public const int UsageError = 2;
|
||||
|
||||
public static Task<int> RunAsync(string[] args, TextWriter output, TextWriter error, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var parseResult = Build(output, error).Parse(args);
|
||||
if (parseResult.Errors.Count > 0)
|
||||
{
|
||||
// Short message and exit code 2, like coreutils, instead of the full help text.
|
||||
foreach (var parseError in parseResult.Errors) error.WriteLine($"hashtool: {parseError.Message}");
|
||||
error.WriteLine("Try 'hashtool --help' for more information.");
|
||||
return Task.FromResult(UsageError);
|
||||
}
|
||||
|
||||
return parseResult.InvokeAsync(new InvocationConfiguration { Output = output, Error = error }, cancellationToken);
|
||||
}
|
||||
|
||||
internal static RootCommand Build(TextWriter output, TextWriter error)
|
||||
{
|
||||
var root = new RootCommand($"Hash Tool {Version} - compute and verify file hashes and checksum files (SHA256SUMS, .md5, .sfv...).");
|
||||
root.Subcommands.Add(HashCommand.Create(output, error));
|
||||
root.Subcommands.Add(VerifyCommand.Create(output, error));
|
||||
root.Subcommands.Add(VerifyCommand.CreateCheck(output, error));
|
||||
root.Subcommands.Add(CreateAlgorithmsCommand(output));
|
||||
return root;
|
||||
}
|
||||
|
||||
internal static string Version =>
|
||||
typeof(HashToolCommand).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
/// <summary><c>-a sha256 -a md5</c> or <c>-a sha256,md5</c>; names as listed by <c>hashtool algorithms</c>.</summary>
|
||||
internal static Option<HashType[]> AlgorithmOption(string description) => new("--algorithm", "-a")
|
||||
{
|
||||
Description = description,
|
||||
HelpName = "name",
|
||||
Arity = ArgumentArity.OneOrMore,
|
||||
CustomParser = ParseAlgorithms
|
||||
};
|
||||
|
||||
private static HashType[] ParseAlgorithms(ArgumentResult result)
|
||||
{
|
||||
var algorithms = new List<HashType>();
|
||||
foreach (var token in result.Tokens)
|
||||
{
|
||||
foreach (var name in token.Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
if (HashAlgorithms.TryParse(name, out var algorithm)) algorithms.Add(algorithm);
|
||||
else result.AddError($"Unknown algorithm '{name}'. Run 'hashtool algorithms' to list the supported ones.");
|
||||
}
|
||||
}
|
||||
|
||||
return [.. algorithms.Distinct()];
|
||||
}
|
||||
|
||||
private static Command CreateAlgorithmsCommand(TextWriter output)
|
||||
{
|
||||
var command = new Command("algorithms", "List the supported hash algorithms.");
|
||||
command.SetAction(_ =>
|
||||
{
|
||||
foreach (var algorithm in HashAlgorithms.All)
|
||||
{
|
||||
var note = algorithm.IsInsecure() ? " (not collision resistant; use for integrity checks only)" : "";
|
||||
output.WriteLine($"{algorithm.ToString().ToLowerInvariant(),-10} {HashAlgorithms.HexLength(algorithm),3} hex digits{note}");
|
||||
}
|
||||
|
||||
return Success;
|
||||
});
|
||||
return command;
|
||||
}
|
||||
|
||||
internal static void ReportError(TextWriter error, string path, Exception exception) =>
|
||||
error.WriteLine($"hashtool: {path}: {Describe(exception)}");
|
||||
|
||||
internal static string Describe(Exception exception) => exception switch
|
||||
{
|
||||
FileNotFoundException or DirectoryNotFoundException => "No such file or directory",
|
||||
UnauthorizedAccessException => "Permission denied",
|
||||
_ => exception.Message
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Path as written to checksum output: relative to <paramref name="relativeTo"/> when given, otherwise absolute. Windows
|
||||
/// separators become '/', so lines need no GNU escaping and the files also work with coreutils.
|
||||
/// </summary>
|
||||
internal static string DisplayPath(string fullPath, string? relativeTo)
|
||||
{
|
||||
var path = relativeTo is null ? fullPath : Path.GetRelativePath(relativeTo, fullPath);
|
||||
return Portable(path);
|
||||
}
|
||||
|
||||
internal static string Portable(string path) => OperatingSystem.IsWindows() ? path.Replace('\\', '/') : path;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HashTool.Cli;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static Task<int> Main(string[] args) => HashToolCommand.RunAsync(args, Console.Out, Console.Error);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.CommandLine;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using HashTool.Core.Checksums;
|
||||
using HashTool.Core.Hashing;
|
||||
|
||||
namespace HashTool.Cli;
|
||||
|
||||
/// <summary><c>hashtool verify</c> (like <c>sha256sum -c</c>) and <c>hashtool check</c> (one file against one hash).</summary>
|
||||
internal static class VerifyCommand
|
||||
{
|
||||
public static Command Create(TextWriter output, TextWriter error)
|
||||
{
|
||||
var files = new Argument<string[]>("checksum-files")
|
||||
{
|
||||
Description = "Checksum files (SHA256SUMS, *.sha256, *.md5, *.sfv, BSD-tagged lists...).",
|
||||
Arity = ArgumentArity.OneOrMore
|
||||
};
|
||||
var algorithm = HashToolCommand.AlgorithmOption("Algorithm to assume when neither the line nor the file name says which one.");
|
||||
algorithm.Arity = ArgumentArity.ExactlyOne;
|
||||
var quiet = new Option<bool>("--quiet", "-q") { Description = "Do not print a line for files that are OK." };
|
||||
var ignoreMissing = new Option<bool>("--ignore-missing") { Description = "Skip listed files that do not exist instead of failing." };
|
||||
|
||||
var command = new Command("verify", "Verify files against checksum files, like 'sha256sum -c'.") { files, algorithm, quiet, ignoreMissing };
|
||||
command.SetAction((result, cancellationToken) => RunAsync(
|
||||
result.GetRequiredValue(files),
|
||||
result.GetValue(algorithm) is [var hint, ..] ? hint : null,
|
||||
result.GetValue(quiet),
|
||||
result.GetValue(ignoreMissing),
|
||||
output, error, cancellationToken));
|
||||
return command;
|
||||
}
|
||||
|
||||
public static Command CreateCheck(TextWriter output, TextWriter error)
|
||||
{
|
||||
var file = new Argument<string>("file") { Description = "The file to check." };
|
||||
var expected = new Option<string>("--expected", "-e") { Description = "The expected hash (hexadecimal).", Required = true, HelpName = "hash" };
|
||||
var algorithm = HashToolCommand.AlgorithmOption("Algorithm of the expected hash (guessed from its length when omitted).");
|
||||
algorithm.Arity = ArgumentArity.ExactlyOne;
|
||||
|
||||
var command = new Command("check", "Check one file against an expected hash.") { file, expected, algorithm };
|
||||
command.SetAction(async (result, cancellationToken) =>
|
||||
{
|
||||
var path = result.GetRequiredValue(file);
|
||||
var hash = HashMatcher.Normalize(result.GetRequiredValue(expected));
|
||||
IReadOnlyList<HashType> candidates = result.GetValue(algorithm) is [var chosen, ..]
|
||||
? [chosen]
|
||||
: HashAlgorithms.CandidatesForHexLength(hash.Length);
|
||||
if (!HashMatcher.IsHex(hash) || candidates.Count == 0)
|
||||
{
|
||||
error.WriteLine($"hashtool: '{result.GetRequiredValue(expected)}' is not a hexadecimal hash of a supported length.");
|
||||
return HashToolCommand.UsageError;
|
||||
}
|
||||
|
||||
var outcome = await CheckAsync(new HashEngine(), path, hash, candidates, cancellationToken).ConfigureAwait(false);
|
||||
output.WriteLine($"{path}: {outcome.Describe()}");
|
||||
if (outcome.Error is { } ex) HashToolCommand.ReportError(error, path, ex);
|
||||
return outcome.IsOk ? HashToolCommand.Success : HashToolCommand.Failure;
|
||||
});
|
||||
return command;
|
||||
}
|
||||
|
||||
internal static async Task<int> RunAsync(IReadOnlyList<string> checksumFiles, HashType? hint, bool quiet, bool ignoreMissing,
|
||||
TextWriter output, TextWriter error, CancellationToken cancellationToken)
|
||||
{
|
||||
var engine = new HashEngine();
|
||||
var exitCode = HashToolCommand.Success;
|
||||
int mismatched = 0, unreadable = 0, malformed = 0;
|
||||
|
||||
foreach (var checksumFile in checksumFiles)
|
||||
{
|
||||
ChecksumDocument document;
|
||||
try
|
||||
{
|
||||
document = await ChecksumParser.ParseFileAsync(checksumFile, hint, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
HashToolCommand.ReportError(error, checksumFile, ex);
|
||||
exitCode = HashToolCommand.UsageError;
|
||||
continue;
|
||||
}
|
||||
|
||||
malformed += document.InvalidLines.Count;
|
||||
if (document.IsEmpty)
|
||||
{
|
||||
error.WriteLine($"hashtool: {checksumFile}: no properly formatted checksum lines found");
|
||||
exitCode = HashToolCommand.UsageError;
|
||||
continue;
|
||||
}
|
||||
|
||||
var directory = Path.GetDirectoryName(Path.GetFullPath(checksumFile))!;
|
||||
foreach (var entry in document.Entries)
|
||||
{
|
||||
// A bare hash in "image.iso.sha256" belongs to "image.iso".
|
||||
var target = entry.FileName is null ? ChecksumFileNames.SidecarTarget(Path.GetFullPath(checksumFile)) : entry.ResolvePath(directory);
|
||||
var shown = entry.FileName ?? (target is null ? checksumFile : Path.GetFileName(target));
|
||||
if (target is null)
|
||||
{
|
||||
error.WriteLine($"hashtool: {checksumFile}:{entry.LineNumber}: refusing to open network or device path '{shown}'");
|
||||
unreadable++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ignoreMissing && !File.Exists(target)) continue;
|
||||
|
||||
IReadOnlyList<HashType> candidates = entry.IsAlgorithmGuessed || entry.Algorithm is null
|
||||
? HashAlgorithms.CandidatesForHexLength(entry.Hash.Length)
|
||||
: [entry.Algorithm.Value];
|
||||
var outcome = await CheckAsync(engine, target, entry.Hash, candidates, cancellationToken).ConfigureAwait(false);
|
||||
if (outcome.Error is not null) unreadable++;
|
||||
else if (!outcome.IsOk) mismatched++;
|
||||
if (!quiet || !outcome.IsOk) output.WriteLine($"{shown}: {outcome.Describe()}");
|
||||
if (outcome.Error is { } ex) HashToolCommand.ReportError(error, shown, ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (malformed > 0) error.WriteLine($"hashtool: WARNING: {Count(malformed, "line is", "lines are")} improperly formatted");
|
||||
if (unreadable > 0) error.WriteLine($"hashtool: WARNING: {Count(unreadable, "listed file", "listed files")} could not be read");
|
||||
if (mismatched > 0) error.WriteLine($"hashtool: WARNING: {Count(mismatched, "computed checksum", "computed checksums")} did NOT match");
|
||||
if (exitCode == HashToolCommand.Success && (mismatched > 0 || unreadable > 0)) exitCode = HashToolCommand.Failure;
|
||||
return exitCode;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
public bool IsOk => Error is null && Match is HashMatch.Match or HashMatch.LegacyByteOrderMatch;
|
||||
|
||||
public string Describe() => Error is not null
|
||||
? "FAILED open or read"
|
||||
: Match switch
|
||||
{
|
||||
HashMatch.Match => "OK",
|
||||
HashMatch.LegacyByteOrderMatch => "OK (CRC32 written in reversed byte order)",
|
||||
HashMatch.LengthMismatch or HashMatch.InvalidExpected => "FAILED (not a valid hash for the algorithm)",
|
||||
_ => "FAILED"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Hashes the file once with every candidate algorithm; any match counts.</summary>
|
||||
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);
|
||||
HashResult[] results;
|
||||
try
|
||||
{
|
||||
results = await engine.ComputeFileAsync(path, candidates, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return new Outcome(HashMatch.Mismatch, null, 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!--
|
||||
Upgrade gate for releases: behaves like an installed Hash Tool 1.1.x, which ships Velopack 0.0.1298. Not part of
|
||||
HashTool.slnx; the release workflow builds and runs it against the freshly packed release files.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
<!-- The old library's dependencies are what 1.1.x users run; auditing them here would only block the gate. -->
|
||||
<NuGetAudit>false</NuGetAudit>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Velopack" VersionOverride="0.0.1298" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Velopack;
|
||||
using Velopack.Locators;
|
||||
using Velopack.Sources;
|
||||
|
||||
// Usage: LegacyClient <releases-dir> <channel> <installed-version> <expected-version> <root-dir> <app-dir> <update-exe> <packages-dir>
|
||||
//
|
||||
// Uses Velopack 0.0.1298 - the library inside Hash Tool 1.1.x - to read the new release feed, pick the update and
|
||||
// download it with its checksum checks, exactly as an installed 1.1.x copy would. Prints the downloaded package path;
|
||||
// the release workflow then lets the old updater apply it and smoke-tests the result.
|
||||
if (args.Length != 8)
|
||||
{
|
||||
Console.Error.WriteLine("usage: LegacyClient <releases-dir> <channel> <installed-version> <expected-version> <root-dir> <app-dir> <update-exe> <packages-dir>");
|
||||
return 2;
|
||||
}
|
||||
|
||||
var (releases, channel, installed, expected, root, app, updateExe, packages) =
|
||||
(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
|
||||
Directory.CreateDirectory(packages);
|
||||
|
||||
var locator = new TestVelopackLocator("HashTool", installed, packages, app, root, updateExe, channel);
|
||||
var manager = new UpdateManager(new SimpleFileSource(new DirectoryInfo(releases)), new UpdateOptions { ExplicitChannel = channel }, locator);
|
||||
|
||||
var update = manager.CheckForUpdates();
|
||||
if (update is null)
|
||||
{
|
||||
Console.Error.WriteLine($"Velopack 0.0.1298 found no update for {installed} on channel '{channel}' in {releases}.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var found = update.TargetFullRelease.Version.ToString();
|
||||
if (!string.Equals(found, expected, StringComparison.Ordinal))
|
||||
{
|
||||
Console.Error.WriteLine($"Velopack 0.0.1298 offered {found}, expected {expected}.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
manager.DownloadUpdates(update);
|
||||
var package = Path.Combine(packages, update.TargetFullRelease.FileName);
|
||||
if (!File.Exists(package))
|
||||
{
|
||||
Console.Error.WriteLine($"The downloaded package is missing: {package}");
|
||||
return 1;
|
||||
}
|
||||
|
||||
Console.Error.WriteLine($"Velopack 0.0.1298 downloaded and verified {update.TargetFullRelease.FileName} ({found}).");
|
||||
Console.WriteLine(package);
|
||||
return 0;
|
||||
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.v3.mtp-v2" />
|
||||
<PackageReference Include="Avalonia.Headless.XUnit" />
|
||||
<PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\HashTool.App\HashTool.App.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\HashTool.Core.Tests\TempDirectory.cs" Link="TempDirectory.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,181 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Resources;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.Core.Configuration;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Guards the 66 translations: same keys and placeholders as English, no stray whitespace, every language wired up in
|
||||
/// Languages.json, the project file and the build output, and no key that the code uses but no file defines (or the reverse).
|
||||
/// </summary>
|
||||
public sealed partial class LocalizationTests
|
||||
{
|
||||
private static readonly IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> Cultures =
|
||||
RepositoryFiles.Translations.Where(t => t.Key.Length > 0).ToDictionary(t => t.Key, t => t.Value);
|
||||
|
||||
private static IReadOnlyList<(string Name, string Code)> LanguagesJson()
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(RepositoryFiles.LangDirectory, "Languages.json")));
|
||||
return document.RootElement.EnumerateArray().Select(e => (e.GetProperty("Name").GetString()!, e.GetProperty("Code").GetString()!)).ToList();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryCultureHasExactlyTheEnglishKeys()
|
||||
{
|
||||
var problems = Cultures.SelectMany(c =>
|
||||
RepositoryFiles.Neutral.Keys.Except(c.Value.Keys).Select(k => $"{c.Key}: missing {k}")
|
||||
.Concat(c.Value.Keys.Except(RepositoryFiles.Neutral.Keys).Select(k => $"{c.Key}: unknown {k}")));
|
||||
|
||||
Assert.Empty(problems);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PlaceholdersMatchEnglish()
|
||||
{
|
||||
var problems = Cultures.SelectMany(c => c.Value
|
||||
.Where(e => RepositoryFiles.Neutral.ContainsKey(e.Key) &&
|
||||
!RepositoryFiles.PlaceholdersOf(e.Value).SequenceEqual(RepositoryFiles.PlaceholdersOf(RepositoryFiles.Neutral[e.Key])))
|
||||
.Select(e => $"{c.Key}: {e.Key} = {e.Value}"));
|
||||
|
||||
Assert.Empty(problems);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValuesAreNotEmptyOrIndented()
|
||||
{
|
||||
var problems = RepositoryFiles.Translations.SelectMany(c => c.Value
|
||||
.Where(e => string.IsNullOrWhiteSpace(e.Value) || e.Value != e.Value.Trim() ||
|
||||
e.Value.Split('\n').Any(line => line != line.Trim()))
|
||||
.Select(e => $"{(c.Key.Length == 0 ? "neutral" : c.Key)}: {e.Key}"));
|
||||
|
||||
Assert.Empty(problems);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LanguagesJsonResxFilesAndProjectAgree()
|
||||
{
|
||||
var codes = LanguagesJson().Select(l => l.Code).ToList();
|
||||
var project = File.ReadAllText(Path.Combine(RepositoryFiles.AppDirectory, "HashTool.App.csproj"));
|
||||
var declared = ProjectCulture().Matches(project).ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
Assert.Equal(codes.Count, codes.Distinct(StringComparer.OrdinalIgnoreCase).Count());
|
||||
Assert.Contains("en-US", codes); // falls back to the neutral English resources
|
||||
Assert.Equal(codes.Where(c => c != "en-US").Order(StringComparer.OrdinalIgnoreCase),
|
||||
Cultures.Keys.Select(f => codes.First(c => c.Equals(f, StringComparison.OrdinalIgnoreCase))).Order(StringComparer.OrdinalIgnoreCase));
|
||||
Assert.Equal(Cultures.Keys.Order(StringComparer.OrdinalIgnoreCase), declared.Keys.Order(StringComparer.OrdinalIgnoreCase));
|
||||
foreach (var (file, culture) in declared)
|
||||
Assert.Equal(codes.First(c => c.Equals(file, StringComparison.OrdinalIgnoreCase)), culture);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EverySatelliteAssemblyLoads()
|
||||
{
|
||||
var resources = new ResourceManager("HashTool.App.Lang.Resources", typeof(App).Assembly);
|
||||
foreach (var (_, code) in LanguagesJson().Where(l => l.Code != "en-US"))
|
||||
{
|
||||
var set = resources.GetResourceSet(CultureInfo.GetCultureInfo(code), createIfNotExists: true, tryParents: false);
|
||||
Assert.True(set is not null, $"No satellite assembly for {code}");
|
||||
Assert.Equal(Cultures[code.ToLowerInvariant()]["Menu_Create"], set.GetString("Menu_Create"));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryKeyUsedByTheCodeExists()
|
||||
{
|
||||
var missing = UsedKeys().Where(k => !RepositoryFiles.Neutral.ContainsKey(k));
|
||||
|
||||
Assert.Empty(missing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryKeyIsUsed()
|
||||
{
|
||||
var used = UsedKeys().ToHashSet(StringComparer.Ordinal);
|
||||
var unused = RepositoryFiles.Neutral.Keys.Where(k => !used.Contains(k));
|
||||
|
||||
Assert.Empty(unused);
|
||||
}
|
||||
|
||||
private static IEnumerable<string> UsedKeys()
|
||||
{
|
||||
var keys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var file in Directory.EnumerateFiles(RepositoryFiles.AppDirectory, "*.*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) ||
|
||||
file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
|
||||
continue;
|
||||
var text = Path.GetExtension(file) switch
|
||||
{
|
||||
".axaml" or ".cs" => File.ReadAllText(file),
|
||||
_ => null
|
||||
};
|
||||
if (text is null) continue;
|
||||
foreach (Match match in XamlKey().Matches(text)) keys.Add(match.Groups[1].Value);
|
||||
foreach (Match match in CodeKey().Matches(text)) keys.Add(match.Groups[1].Value);
|
||||
}
|
||||
|
||||
// Built at runtime: $"Theme_{style}".
|
||||
foreach (var style in Enum.GetValues<AppThemeStyle>()) keys.Add($"Theme_{style}");
|
||||
return keys;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"Localization\[(AppTitle|[A-Za-z]+_[A-Za-z0-9_]+)\]")]
|
||||
private static partial Regex XamlKey();
|
||||
|
||||
[GeneratedRegex(@"""((?:AppTitle|(?:About|Btn|Dev|Dialog|Doc|EmptyState|Error|Export|FileType|Filter|Font|Help|Lang|Lbl|Menu|Msg|Settings|Shell|Size|Status|Theme|Tip|Title|Unit|Watermark)_[A-Za-z0-9_]+))""")]
|
||||
private static partial Regex CodeKey();
|
||||
|
||||
[GeneratedRegex(@"<EmbeddedResource Update=""Lang\\Resources\.([^""]+)\.resx"" Culture=""([^""]+)"" />")]
|
||||
private static partial Regex ProjectCulture();
|
||||
|
||||
// ------------------------------------------------------------------ system language detection
|
||||
|
||||
private static IReadOnlyList<LanguageItem> Languages() => LanguagesJson().Select(l => new LanguageItem(l.Name, l.Code)).ToList();
|
||||
|
||||
[Theory]
|
||||
[InlineData("en-US", "en-US")]
|
||||
[InlineData("en-GB", "en-GB")]
|
||||
[InlineData("en-AU", "en-GB")]
|
||||
[InlineData("en-CA", "en-US")]
|
||||
[InlineData("vi-VN", "vi-VN")]
|
||||
[InlineData("zh-CN", "zh-Hans-CN")]
|
||||
[InlineData("zh-SG", "zh-Hans-SG")]
|
||||
[InlineData("zh-TW", "zh-Hant")]
|
||||
[InlineData("zh-HK", "zh-Hant")]
|
||||
[InlineData("zh-Hant-TW", "zh-Hant")]
|
||||
[InlineData("es-ES", "es-ES")]
|
||||
[InlineData("es-MX", "es-419")]
|
||||
[InlineData("es-AR", "es-419")]
|
||||
[InlineData("pt-PT", "pt-BR")]
|
||||
[InlineData("de-LU", "de-DE")]
|
||||
[InlineData("de-AT", "de-AT")]
|
||||
[InlineData("fr-CA", "fr-FR")]
|
||||
[InlineData("fi-FI", "fi-FI")]
|
||||
[InlineData("fil-PH", "fil-PH")]
|
||||
[InlineData("el-GR", "el-GR")]
|
||||
[InlineData("nn-NO", "nb-NO")]
|
||||
[InlineData("sr-Latn-RS", "sr-Cyrl-RS")]
|
||||
[InlineData("ar-EG", "ar")]
|
||||
[InlineData("tr-TR", "tr-TR")]
|
||||
[InlineData("sw-KE", "en-US")]
|
||||
public void DetectSystemLanguage_MapsCultures(string system, string expected)
|
||||
{
|
||||
var culture = CultureInfo.GetCultureInfo(system);
|
||||
|
||||
Assert.Equal(expected, LocalizationService.DetectSystemLanguage(Languages(), culture, culture));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DetectSystemLanguage_FallsBackToTheRegionalFormat()
|
||||
{
|
||||
Assert.Equal("ja-JP", LocalizationService.DetectSystemLanguage(Languages(), CultureInfo.GetCultureInfo("sw-KE"), CultureInfo.GetCultureInfo("ja-JP")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Reads source files of the repository (translations, views) from the checkout the tests were built from.</summary>
|
||||
internal static partial class RepositoryFiles
|
||||
{
|
||||
public static string Root { get; } = FindRoot();
|
||||
|
||||
public static string AppDirectory => Path.Combine(Root, "src", "HashTool.App");
|
||||
|
||||
public static string LangDirectory => Path.Combine(AppDirectory, "Lang");
|
||||
|
||||
/// <summary>The neutral (English) resx and every culture resx, keyed by file culture ("" for neutral).</summary>
|
||||
public static IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> Translations { get; } = LoadTranslations();
|
||||
|
||||
public static IReadOnlyDictionary<string, string> Neutral => Translations[""];
|
||||
|
||||
public static IEnumerable<string> PlaceholdersOf(string value) =>
|
||||
Placeholder().Matches(value).Select(m => m.Value).Order(StringComparer.Ordinal);
|
||||
|
||||
[GeneratedRegex(@"\{\d+(?:,[^}:]+)?(?::[^}]*)?\}")]
|
||||
private static partial Regex Placeholder();
|
||||
|
||||
private static string FindRoot()
|
||||
{
|
||||
for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent)
|
||||
{
|
||||
if (File.Exists(Path.Combine(directory.FullName, "HashTool.slnx"))) return directory.FullName;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Could not find the repository root (HashTool.slnx).");
|
||||
}
|
||||
|
||||
private static Dictionary<string, IReadOnlyDictionary<string, string>> LoadTranslations()
|
||||
{
|
||||
var result = new Dictionary<string, IReadOnlyDictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var file in Directory.GetFiles(LangDirectory, "Resources*.resx"))
|
||||
{
|
||||
var parts = Path.GetFileName(file).Split('.');
|
||||
var culture = parts.Length == 2 ? "" : parts[1];
|
||||
var entries = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var data in XDocument.Load(file, LoadOptions.PreserveWhitespace).Root!.Elements("data"))
|
||||
entries[(string)data.Attribute("name")!] = (string?)data.Element("value") ?? "";
|
||||
result[culture] = entries;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Avalonia;
|
||||
using Avalonia.Headless;
|
||||
using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Tests;
|
||||
|
||||
[assembly: AvaloniaTestApplication(typeof(TestApp))]
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Runs the real <see cref="App"/> on Avalonia's headless platform, with settings and logs in a temporary folder.</summary>
|
||||
public static class TestApp
|
||||
{
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
{
|
||||
Environment.SetEnvironmentVariable(AppPaths.DataDirectoryVariable, Directory.CreateTempSubdirectory("hashtool-app-tests-").FullName);
|
||||
return AppBuilder.Configure<App>().UseHeadless(new AvaloniaHeadlessPlatformOptions()).WithInterFont();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using HashTool.App.Infrastructure;
|
||||
using HashTool.App.Infrastructure.Logging;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.App.Views.Controls;
|
||||
using HashTool.Core.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
public sealed class HighlightTextBlockTests
|
||||
{
|
||||
[Fact]
|
||||
public void Split_EmitsTheTailOnce()
|
||||
{
|
||||
Assert.Equal([("rep", true), ("ort.pdf", false)], HighlightTextBlock.Split("report.pdf", "rep"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Split_IsCaseInsensitiveAndFindsEveryMatch()
|
||||
{
|
||||
Assert.Equal([("a", false), ("X", true), ("a", false), ("x", true)], HighlightTextBlock.Split("aXax", "x"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Split_WithoutMatch_ReturnsTheText()
|
||||
{
|
||||
Assert.Equal([("report.pdf", false)], HighlightTextBlock.Split("report.pdf", "zip"));
|
||||
Assert.Equal([("abc", false)], HighlightTextBlock.Split("abc", ""));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class AppCommandLineTests
|
||||
{
|
||||
[Fact]
|
||||
public void Parse_VerbAndPaths()
|
||||
{
|
||||
var parsed = AppCommandLine.Parse(["--verify", "a.sha256", "sub/b.md5"], workingDirectory: Path.GetTempPath());
|
||||
|
||||
Assert.Equal(ActivationVerb.Verify, parsed.Verb);
|
||||
Assert.Equal([Path.Combine(Path.GetTempPath(), "a.sha256"), Path.GetFullPath(Path.Combine(Path.GetTempPath(), "sub/b.md5"))], parsed.Paths);
|
||||
Assert.False(parsed.SmokeTest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_SmokeTestOptions()
|
||||
{
|
||||
var parsed = AppCommandLine.Parse(["--smoke-test", "--smoke-out", "r.json", "--expect-version", "1.2.0", "--wait-pid", "42", "--unknown"]);
|
||||
|
||||
Assert.True(parsed.SmokeTest);
|
||||
Assert.Equal("r.json", parsed.SmokeOutput);
|
||||
Assert.Equal("1.2.0", parsed.ExpectedVersion);
|
||||
Assert.Equal(42, parsed.WaitPid);
|
||||
Assert.Empty(parsed.Paths);
|
||||
Assert.Null(parsed.ToRequest());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FilesFrom_DeletesOnlyTheAppsOwnTemporaryList()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
var ownList = Path.Combine(Path.GetTempPath(), $"hashtool-{Guid.NewGuid():N}.txt");
|
||||
File.WriteAllLines(ownList, [Path.Combine(temp.Path, "a.bin")]);
|
||||
var userFile = temp.File("important.txt", Path.Combine(temp.Path, "b.bin"));
|
||||
|
||||
var fromOwn = AppCommandLine.Parse(["--create", "--files-from", ownList]);
|
||||
var fromUser = AppCommandLine.Parse(["--files-from", userFile]);
|
||||
|
||||
Assert.Equal([Path.Combine(temp.Path, "a.bin")], fromOwn.Paths);
|
||||
Assert.False(File.Exists(ownList));
|
||||
Assert.Equal([Path.Combine(temp.Path, "b.bin")], fromUser.Paths);
|
||||
Assert.True(File.Exists(userFile));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TextHelperTests
|
||||
{
|
||||
[Fact]
|
||||
public void ReleaseNotes_MarkdownBecomesPlainText()
|
||||
{
|
||||
var text = UpdateViewModel.ToPlainText("## Added\n\n- **CLI** `hashtool`\n- See [docs](https://example.com)\n\n\n\nEnd");
|
||||
|
||||
Assert.Equal("Added\n\n• CLI hashtool\n• See docs\n\nEnd", text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PathSanitizer_MasksUserFolders()
|
||||
{
|
||||
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
var sanitized = PathSanitizer.Shared.Sanitize($"Could not read {Path.Combine(home, "Documents", "secret.txt")}");
|
||||
|
||||
Assert.DoesNotContain(home, sanitized, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.EndsWith("secret.txt", sanitized);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("C:/data", "C:/data/a/b.txt", "a/b.txt")]
|
||||
[InlineData("C:/data", "C:/data/b.txt", "b.txt")]
|
||||
public void RelativePath_UsesForwardSlashes(string baseDirectory, string file, string expected)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
Assert.Equal(expected, CreateHashViewModel.RelativePath(baseDirectory, file));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LogEntry_UsesInvariantTimestamps()
|
||||
{
|
||||
var entry = new LogEntry(new DateTimeOffset(2026, 10, 15, 8, 30, 5, 123, TimeSpan.Zero), Microsoft.Extensions.Logging.LogLevel.Warning, "Test", "message");
|
||||
|
||||
Assert.Equal("08:30:05.123 [WARN] Test: message", entry.ToString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Headless.XUnit;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using HashTool.App.Services;
|
||||
using HashTool.App.ViewModels;
|
||||
using HashTool.App.Views;
|
||||
using HashTool.Core.Hashing;
|
||||
using HashTool.Core.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.App.Tests;
|
||||
|
||||
/// <summary>Renders the real window and pages on Avalonia's headless platform.</summary>
|
||||
public sealed class ViewTests
|
||||
{
|
||||
private const string Sha256Of123456789 = "15E2B0D3C33891EBB0F1EF609EC419420C20E320CE94C65FBC8C3312448EB225";
|
||||
|
||||
[AvaloniaFact]
|
||||
public void EveryPageRendersWithoutMissingTranslations()
|
||||
{
|
||||
var main = AppHost.Get<MainWindowViewModel>();
|
||||
var localization = AppHost.Get<LocalizationService>();
|
||||
var window = new MainWindow { DataContext = main };
|
||||
window.Show();
|
||||
try
|
||||
{
|
||||
foreach (var code in new[] { "en-US", "vi-VN", "ar", "ja-JP", "de-DE", "fil-PH" })
|
||||
{
|
||||
localization.SelectedLanguage = localization.Find(code);
|
||||
Assert.Equal(code is "ar" ? FlowDirection.RightToLeft : FlowDirection.LeftToRight, window.FlowDirection);
|
||||
foreach (var page in new[] { "Create", "Check", "Settings", "Update", "About", "Developer" })
|
||||
{
|
||||
main.NavigateCommand.Execute(page);
|
||||
Dispatcher.UIThread.RunJobs();
|
||||
window.UpdateLayout();
|
||||
|
||||
var missing = window.GetVisualDescendants().OfType<TextBlock>()
|
||||
.Select(t => t.Text)
|
||||
.Where(t => t is not null && t.StartsWith('[') && t.EndsWith(']'))
|
||||
.ToList();
|
||||
Assert.True(missing.Count == 0, $"{code}/{page}: {string.Join(", ", missing)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
localization.SelectedLanguage = localization.AvailableLanguages[0];
|
||||
main.NavigateCommand.Execute("Create");
|
||||
window.Close();
|
||||
}
|
||||
}
|
||||
|
||||
[AvaloniaFact]
|
||||
public async Task CreateAndVerify_FolderInputAndChecksumFile()
|
||||
{
|
||||
using var temp = new TempDirectory();
|
||||
temp.File("folder/sub/check.txt", "123456789");
|
||||
var create = AppHost.Get<CreateHashViewModel>();
|
||||
var check = AppHost.Get<CheckHashViewModel>();
|
||||
create.SelectedAlgorithm = HashType.SHA256;
|
||||
|
||||
// 1.x crashed when a folder was dropped.
|
||||
await create.AddPathsAsync([Path.Combine(temp.Path, "folder")]);
|
||||
await create.RunAllCommand.ExecuteAsync(null);
|
||||
var created = Assert.Single(create.Items);
|
||||
Assert.Equal(Sha256Of123456789, created.ResultHash, ignoreCase: true);
|
||||
|
||||
var manifest = temp.File("folder/SHA256SUMS", $"{Sha256Of123456789.ToLowerInvariant()} sub/check.txt\n");
|
||||
await check.AddPathsAsync([manifest]);
|
||||
await check.RunAllCommand.ExecuteAsync(null);
|
||||
var verified = Assert.Single(check.Items);
|
||||
Assert.True(verified.IsMatch);
|
||||
Assert.Equal(ItemStatus.Valid, verified.Status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using HashTool.Core.Tests;
|
||||
using Xunit;
|
||||
|
||||
namespace HashTool.Cli.Tests;
|
||||
|
||||
public sealed class CliTests : IDisposable
|
||||
{
|
||||
private const string Sha256Of123456789 = "15e2b0d3c33891ebb0f1ef609ec419420c20e320ce94c65fbc8c3312448eb225";
|
||||
private const string Sha256OfHello = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
|
||||
|
||||
private readonly TempDirectory _temp = new();
|
||||
|
||||
public void Dispose() => _temp.Dispose();
|
||||
|
||||
/// <summary>The CLI writes Windows paths with '/' separators.</summary>
|
||||
private static string Shown(string path) => OperatingSystem.IsWindows() ? path.Replace('\\', '/') : path;
|
||||
|
||||
private static async Task<(int ExitCode, string Output, string Error)> RunAsync(params string[] args)
|
||||
{
|
||||
using var output = new StringWriter { NewLine = "\n" };
|
||||
using var error = new StringWriter { NewLine = "\n" };
|
||||
var exitCode = await HashToolCommand.RunAsync(args, output, error, TestContext.Current.CancellationToken);
|
||||
return (exitCode, output.ToString(), error.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_SingleFile_PrintsGnuLine()
|
||||
{
|
||||
var file = _temp.File("check.txt", "123456789");
|
||||
|
||||
var (exitCode, output, error) = await RunAsync("hash", file);
|
||||
|
||||
Assert.Equal(0, exitCode);
|
||||
Assert.Equal($"{Sha256Of123456789} {Shown(file)}\n", output);
|
||||
Assert.Empty(error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_SeveralAlgorithms_UsesTaggedFormat()
|
||||
{
|
||||
var file = _temp.File("check.txt", "123456789");
|
||||
|
||||
var (exitCode, output, _) = await RunAsync("hash", file, "-a", "sha256,crc32", "--uppercase");
|
||||
|
||||
Assert.Equal(0, exitCode);
|
||||
Assert.Contains($"SHA256 ({Shown(file)}) = {Sha256Of123456789.ToUpperInvariant()}", output);
|
||||
Assert.Contains($"CRC32 ({Shown(file)}) = CBF43926", output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_GnuWithSeveralAlgorithms_IsUsageError()
|
||||
{
|
||||
var file = _temp.File("check.txt", "123456789");
|
||||
|
||||
var (exitCode, _, error) = await RunAsync("hash", file, "-a", "sha256", "-a", "md5", "-f", "gnu");
|
||||
|
||||
Assert.Equal(2, exitCode);
|
||||
Assert.Contains("single algorithm", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_UnknownAlgorithm_IsUsageError()
|
||||
{
|
||||
var (exitCode, output, error) = await RunAsync("hash", "x", "-a", "sha3");
|
||||
|
||||
Assert.Equal(2, exitCode);
|
||||
Assert.Empty(output);
|
||||
Assert.Contains("Unknown algorithm 'sha3'", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_Directory_RequiresRecursive()
|
||||
{
|
||||
_temp.File("dir/a.txt", "hello");
|
||||
|
||||
var (exitCode, _, error) = await RunAsync("hash", Path.Combine(_temp.Path, "dir"));
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Contains("is a directory", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hash_ToOutputFile_WritesRelativePathsThatVerify()
|
||||
{
|
||||
_temp.File("data/check.txt", "123456789");
|
||||
_temp.File("data/sub/hello.txt", "hello");
|
||||
var manifest = Path.Combine(_temp.Path, "data", "SHA256SUMS");
|
||||
|
||||
var hash = await RunAsync("hash", "-r", Path.Combine(_temp.Path, "data"), "-o", manifest);
|
||||
var content = await File.ReadAllTextAsync(manifest, TestContext.Current.CancellationToken);
|
||||
var verify = await RunAsync("verify", manifest);
|
||||
|
||||
Assert.Equal(0, hash.ExitCode);
|
||||
Assert.Contains($"{Sha256Of123456789} check.txt\n", content);
|
||||
Assert.Contains($"{Sha256OfHello} sub/hello.txt\n", content);
|
||||
Assert.Equal(0, verify.ExitCode);
|
||||
Assert.Contains("check.txt: OK", verify.Output);
|
||||
Assert.Contains("sub/hello.txt: OK", verify.Output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_ReportsMismatchAndMissingFiles()
|
||||
{
|
||||
_temp.File("a.txt", "changed");
|
||||
var manifest = _temp.File("SHA256SUMS", $"{Sha256OfHello} a.txt\n{Sha256OfHello} missing.txt\nnot a checksum line\n");
|
||||
|
||||
var (exitCode, output, error) = await RunAsync("verify", manifest);
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Contains("a.txt: FAILED\n", output);
|
||||
Assert.Contains("missing.txt: FAILED open or read", output);
|
||||
Assert.Contains("1 line is improperly formatted", error);
|
||||
Assert.Contains("1 listed file could not be read", error);
|
||||
Assert.Contains("1 computed checksum did NOT match", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_IgnoreMissing_And_Quiet()
|
||||
{
|
||||
_temp.File("a.txt", "hello");
|
||||
var manifest = _temp.File("SHA256SUMS", $"{Sha256OfHello} a.txt\n{Sha256OfHello} missing.txt\n");
|
||||
|
||||
var (exitCode, output, _) = await RunAsync("verify", manifest, "--ignore-missing", "--quiet");
|
||||
|
||||
Assert.Equal(0, exitCode);
|
||||
Assert.Empty(output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_SidecarWithBareHash()
|
||||
{
|
||||
_temp.File("image.iso", "hello");
|
||||
var sidecar = _temp.File("image.iso.sha256", Sha256OfHello.ToUpperInvariant() + "\n");
|
||||
|
||||
var (exitCode, output, _) = await RunAsync("verify", sidecar);
|
||||
|
||||
Assert.Equal(0, exitCode);
|
||||
Assert.Equal("image.iso: OK\n", output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_RefusesNetworkPaths()
|
||||
{
|
||||
var manifest = _temp.File("SHA256SUMS", $@"{Sha256OfHello} \\server\share\payload.bin" + "\n");
|
||||
|
||||
var (exitCode, _, error) = await RunAsync("verify", manifest);
|
||||
|
||||
Assert.Equal(1, exitCode);
|
||||
Assert.Contains("refusing to open network or device path", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_UnreadableChecksumFile_IsExitCode2()
|
||||
{
|
||||
var (exitCode, _, error) = await RunAsync("verify", Path.Combine(_temp.Path, "nope.sha256"));
|
||||
|
||||
Assert.Equal(2, exitCode);
|
||||
Assert.Contains("nope.sha256", error);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("CBF43926", 0, "check.txt: OK\n")]
|
||||
[InlineData("2639F4CB", 0, "check.txt: OK (CRC32 written in reversed byte order)\n")]
|
||||
[InlineData("00000000", 1, "check.txt: FAILED\n")]
|
||||
public async Task Check_ComparesAgainstExpectedCrc32(string expected, int exitCode, string message)
|
||||
{
|
||||
var file = _temp.File("check.txt", "123456789");
|
||||
|
||||
var result = await RunAsync("check", file, "--expected", expected, "-a", "crc32");
|
||||
|
||||
Assert.Equal(exitCode, result.ExitCode);
|
||||
Assert.Equal(file + message[message.IndexOf(':')..], result.Output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_GuessesAlgorithmFromLength()
|
||||
{
|
||||
var file = _temp.File("check.txt", "123456789");
|
||||
|
||||
var (exitCode, _, _) = await RunAsync("check", file, "-e", Sha256Of123456789.ToUpperInvariant());
|
||||
|
||||
Assert.Equal(0, exitCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_RejectsNonHex()
|
||||
{
|
||||
var (exitCode, _, error) = await RunAsync("check", "whatever", "-e", "xyz");
|
||||
|
||||
Assert.Equal(2, exitCode);
|
||||
Assert.Contains("not a hexadecimal hash", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Algorithms_ListsEverySupportedAlgorithm()
|
||||
{
|
||||
var (exitCode, output, _) = await RunAsync("algorithms");
|
||||
|
||||
Assert.Equal(0, exitCode);
|
||||
foreach (var name in new[] { "md5", "sha1", "sha256", "sha384", "sha512", "blake3", "xxhash32", "xxhash64", "xxhash3", "xxhash128", "crc32" })
|
||||
Assert.Contains(name, output);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xunit.v3.mtp-v2" />
|
||||
<PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\HashTool.Cli\HashTool.Cli.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\HashTool.Core.Tests\TempDirectory.cs" Link="TempDirectory.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Reference in new issue
Block a user