diff --git a/HashTool.slnx b/HashTool.slnx
index 30cd776..2601e8e 100644
--- a/HashTool.slnx
+++ b/HashTool.slnx
@@ -1,9 +1,15 @@
+
+
+
+
+
+
diff --git a/bench/HashTool.Benchmarks/HashTool.Benchmarks.csproj b/bench/HashTool.Benchmarks/HashTool.Benchmarks.csproj
new file mode 100644
index 0000000..df67cf2
--- /dev/null
+++ b/bench/HashTool.Benchmarks/HashTool.Benchmarks.csproj
@@ -0,0 +1,16 @@
+
+
+ Exe
+ false
+
+ true
+
+
+
+
+
+
+
+
+
+
diff --git a/bench/HashTool.Benchmarks/HashingBenchmarks.cs b/bench/HashTool.Benchmarks/HashingBenchmarks.cs
new file mode 100644
index 0000000..6475d6f
--- /dev/null
+++ b/bench/HashTool.Benchmarks/HashingBenchmarks.cs
@@ -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;
+
+/// Large-file throughput of against the one-line BCL approach.
+[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 Sha256() => _engine.ComputeFileAsync(_file, HashType.SHA256);
+
+ [Benchmark]
+ public Task Blake3() => _engine.ComputeFileAsync(_file, HashType.BLAKE3);
+
+ [Benchmark]
+ public Task XxHash3() => _engine.ComputeFileAsync(_file, HashType.XxHash3);
+
+ [Benchmark]
+ public Task Crc32() => _engine.ComputeFileAsync(_file, HashType.CRC32);
+
+ /// One read of the file for three algorithms (1.x read the file once per algorithm).
+ [Benchmark]
+ public Task Sha256_Md5_Crc32_OnePass() => _engine.ComputeFileAsync(_file, [HashType.SHA256, HashType.MD5, HashType.CRC32]);
+}
+
+/// Many small files: sequential hashing against .
+[MemoryDiagnoser]
+public class SmallFilesBenchmarks
+{
+ private readonly HashEngine _engine = new();
+ private string _directory = null!;
+ private List _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
+ {
+ 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;
+ }
+}
diff --git a/bench/HashTool.Benchmarks/Program.cs b/bench/HashTool.Benchmarks/Program.cs
new file mode 100644
index 0000000..eb5272a
--- /dev/null
+++ b/bench/HashTool.Benchmarks/Program.cs
@@ -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);
+}
diff --git a/build/linux/hashtool.png b/build/linux/hashtool.png
new file mode 100644
index 0000000..7194e41
Binary files /dev/null and b/build/linux/hashtool.png differ
diff --git a/build/macos/Info.plist b/build/macos/Info.plist
new file mode 100644
index 0000000..09776b3
--- /dev/null
+++ b/build/macos/Info.plist
@@ -0,0 +1,86 @@
+
+
+
+
+
+ CFBundleName
+ Hash Tool
+ CFBundleDisplayName
+ Hash Tool
+ CFBundleIdentifier
+ com.HashTool.HashTool
+ CFBundleVersion
+ @VERSION@
+ CFBundleShortVersionString
+ @VERSION@
+ CFBundlePackageType
+ APPL
+ CFBundleSignature
+ ????
+ CFBundleExecutable
+ CheckHash
+ CFBundleIconFile
+ icons.icns
+ NSPrincipalClass
+ NSApplication
+ NSHighResolutionCapable
+
+ LSApplicationCategoryType
+ public.app-category.utilities
+
+ CFBundleDocumentTypes
+
+
+ CFBundleTypeName
+ Checksum File
+ CFBundleTypeRole
+ Viewer
+ LSHandlerRank
+ Alternate
+ CFBundleTypeExtensions
+
+ md5
+ md5sum
+ sha1
+ sha1sum
+ sha256
+ sha256sum
+ sha384
+ sha384sum
+ sha512
+ sha512sum
+ blake3
+ b3
+ b3sum
+ xxhash32
+ xxh32
+ xxhash64
+ xxh64
+ xxhash3
+ xxh3
+ xxhash128
+ xxh128
+ crc32
+ sfv
+
+
+
+ CFBundleTypeName
+ File or Folder
+ CFBundleTypeRole
+ Viewer
+ LSHandlerRank
+ None
+ LSItemContentTypes
+
+ public.data
+ public.folder
+
+
+
+
+
diff --git a/dotnet-tools.json b/dotnet-tools.json
new file mode 100644
index 0000000..27531fc
--- /dev/null
+++ b/dotnet-tools.json
@@ -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
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/HashTool.Cli/HashCommand.cs b/src/HashTool.Cli/HashCommand.cs
new file mode 100644
index 0000000..760944a
--- /dev/null
+++ b/src/HashTool.Cli/HashCommand.cs
@@ -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;
+
+/// hashtool hash: prints or writes checksum lines for files and folders.
+internal static class HashCommand
+{
+ private sealed record Input(string FullPath, string Display);
+
+ public static Command Create(TextWriter output, TextWriter error)
+ {
+ var paths = new Argument("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("--recursive", "-r") { Description = "Hash every file inside the given folders." };
+ var hidden = new Option("--hidden") { Description = "Include hidden and system files when walking folders." };
+ var format = new Option("--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("--output", "-o")
+ { Description = "Write to this file instead of the console. Paths inside are relative to its folder.", HelpName = "file" };
+ var upper = new Option("--uppercase", "-u") { Description = "Print hexadecimal digits in upper case." };
+ var jobs = new Option("--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 Paths,
+ IReadOnlyList Algorithms,
+ bool Recursive,
+ bool IncludeHidden,
+ ExportFormat? Format,
+ FileInfo? OutputFile,
+ HexCase LetterCase,
+ int Jobs);
+
+ internal static async Task 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();
+ 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 Expand(Request request, string? relativeTo, TextWriter error, ref int failures, CancellationToken cancellationToken)
+ {
+ var inputs = new List();
+ var seen = new HashSet(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;
+ }
+ }
+}
diff --git a/src/HashTool.Cli/HashTool.Cli.csproj b/src/HashTool.Cli/HashTool.Cli.csproj
new file mode 100644
index 0000000..807d716
--- /dev/null
+++ b/src/HashTool.Cli/HashTool.Cli.csproj
@@ -0,0 +1,27 @@
+
+
+ Exe
+ HashTool.Cli
+ hashtool
+ Hash Tool CLI
+ Command-line companion of Hash Tool: compute and verify file hashes and checksum files.
+
+ true
+ true
+ true
+
+ en
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/HashTool.Cli/HashToolCommand.cs b/src/HashTool.Cli/HashToolCommand.cs
new file mode 100644
index 0000000..4a95893
--- /dev/null
+++ b/src/HashTool.Cli/HashToolCommand.cs
@@ -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;
+
+///
+/// hashtool: compute and verify hashes from the command line. Exit codes follow coreutils' sha256sum:
+/// 0 = success, 1 = a file failed or did not match, 2 = usage error or unreadable checksum file.
+///
+public static class HashToolCommand
+{
+ public const int Success = 0;
+ public const int Failure = 1;
+ public const int UsageError = 2;
+
+ public static Task 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()?.InformationalVersion ?? "0.0.0";
+
+ /// -a sha256 -a md5 or -a sha256,md5; names as listed by hashtool algorithms.
+ internal static Option 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();
+ 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
+ };
+
+ ///
+ /// Path as written to checksum output: relative to when given, otherwise absolute. Windows
+ /// separators become '/', so lines need no GNU escaping and the files also work with coreutils.
+ ///
+ 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;
+}
+
diff --git a/src/HashTool.Cli/Program.cs b/src/HashTool.Cli/Program.cs
new file mode 100644
index 0000000..5dfc962
--- /dev/null
+++ b/src/HashTool.Cli/Program.cs
@@ -0,0 +1,9 @@
+using System;
+using System.Threading.Tasks;
+
+namespace HashTool.Cli;
+
+internal static class Program
+{
+ private static Task Main(string[] args) => HashToolCommand.RunAsync(args, Console.Out, Console.Error);
+}
diff --git a/src/HashTool.Cli/VerifyCommand.cs b/src/HashTool.Cli/VerifyCommand.cs
new file mode 100644
index 0000000..4247403
--- /dev/null
+++ b/src/HashTool.Cli/VerifyCommand.cs
@@ -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;
+
+/// hashtool verify (like sha256sum -c) and hashtool check (one file against one hash).
+internal static class VerifyCommand
+{
+ public static Command Create(TextWriter output, TextWriter error)
+ {
+ var files = new Argument("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("--quiet", "-q") { Description = "Do not print a line for files that are OK." };
+ var ignoreMissing = new Option("--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("file") { Description = "The file to check." };
+ var expected = new Option("--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 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 RunAsync(IReadOnlyList 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 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"
+ };
+ }
+
+ /// Hashes the file once with every candidate algorithm; any match counts.
+ internal static async Task CheckAsync(HashEngine engine, string path, string expected, IReadOnlyList 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);
+ }
+}
diff --git a/tests/Compat/LegacyClient/LegacyClient.csproj b/tests/Compat/LegacyClient/LegacyClient.csproj
new file mode 100644
index 0000000..8cd2dcb
--- /dev/null
+++ b/tests/Compat/LegacyClient/LegacyClient.csproj
@@ -0,0 +1,16 @@
+
+
+
+ Exe
+ false
+
+ false
+
+
+
+
+
+
diff --git a/tests/Compat/LegacyClient/Program.cs b/tests/Compat/LegacyClient/Program.cs
new file mode 100644
index 0000000..e9f02ab
--- /dev/null
+++ b/tests/Compat/LegacyClient/Program.cs
@@ -0,0 +1,49 @@
+using System;
+using System.IO;
+using Velopack;
+using Velopack.Locators;
+using Velopack.Sources;
+
+// Usage: LegacyClient
+//
+// 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 ");
+ 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;
diff --git a/tests/HashTool.App.Tests/HashTool.App.Tests.csproj b/tests/HashTool.App.Tests/HashTool.App.Tests.csproj
new file mode 100644
index 0000000..5d96372
--- /dev/null
+++ b/tests/HashTool.App.Tests/HashTool.App.Tests.csproj
@@ -0,0 +1,21 @@
+
+
+ Exe
+ false
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/HashTool.App.Tests/LocalizationTests.cs b/tests/HashTool.App.Tests/LocalizationTests.cs
new file mode 100644
index 0000000..4d681b8
--- /dev/null
+++ b/tests/HashTool.App.Tests/LocalizationTests.cs
@@ -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;
+
+///
+/// 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).
+///
+public sealed partial class LocalizationTests
+{
+ private static readonly IReadOnlyDictionary> 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 UsedKeys()
+ {
+ var keys = new HashSet(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()) 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(@"")]
+ private static partial Regex ProjectCulture();
+
+ // ------------------------------------------------------------------ system language detection
+
+ private static IReadOnlyList 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")));
+ }
+}
diff --git a/tests/HashTool.App.Tests/RepositoryFiles.cs b/tests/HashTool.App.Tests/RepositoryFiles.cs
new file mode 100644
index 0000000..bbbf458
--- /dev/null
+++ b/tests/HashTool.App.Tests/RepositoryFiles.cs
@@ -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;
+
+/// Reads source files of the repository (translations, views) from the checkout the tests were built from.
+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");
+
+ /// The neutral (English) resx and every culture resx, keyed by file culture ("" for neutral).
+ public static IReadOnlyDictionary> Translations { get; } = LoadTranslations();
+
+ public static IReadOnlyDictionary Neutral => Translations[""];
+
+ public static IEnumerable 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> LoadTranslations()
+ {
+ var result = new Dictionary>(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(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;
+ }
+}
diff --git a/tests/HashTool.App.Tests/TestApp.cs b/tests/HashTool.App.Tests/TestApp.cs
new file mode 100644
index 0000000..5fa937c
--- /dev/null
+++ b/tests/HashTool.App.Tests/TestApp.cs
@@ -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;
+
+/// Runs the real on Avalonia's headless platform, with settings and logs in a temporary folder.
+public static class TestApp
+{
+ public static AppBuilder BuildAvaloniaApp()
+ {
+ Environment.SetEnvironmentVariable(AppPaths.DataDirectoryVariable, Directory.CreateTempSubdirectory("hashtool-app-tests-").FullName);
+ return AppBuilder.Configure().UseHeadless(new AvaloniaHeadlessPlatformOptions()).WithInterFont();
+ }
+}
diff --git a/tests/HashTool.App.Tests/UnitTests.cs b/tests/HashTool.App.Tests/UnitTests.cs
new file mode 100644
index 0000000..aba676d
--- /dev/null
+++ b/tests/HashTool.App.Tests/UnitTests.cs
@@ -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());
+ }
+}
diff --git a/tests/HashTool.App.Tests/ViewTests.cs b/tests/HashTool.App.Tests/ViewTests.cs
new file mode 100644
index 0000000..6d533f6
--- /dev/null
+++ b/tests/HashTool.App.Tests/ViewTests.cs
@@ -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;
+
+/// Renders the real window and pages on Avalonia's headless platform.
+public sealed class ViewTests
+{
+ private const string Sha256Of123456789 = "15E2B0D3C33891EBB0F1EF609EC419420C20E320CE94C65FBC8C3312448EB225";
+
+ [AvaloniaFact]
+ public void EveryPageRendersWithoutMissingTranslations()
+ {
+ var main = AppHost.Get();
+ var localization = AppHost.Get();
+ 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()
+ .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();
+ var check = AppHost.Get();
+ 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);
+ }
+}
diff --git a/tests/HashTool.Cli.Tests/CliTests.cs b/tests/HashTool.Cli.Tests/CliTests.cs
new file mode 100644
index 0000000..618c9d1
--- /dev/null
+++ b/tests/HashTool.Cli.Tests/CliTests.cs
@@ -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();
+
+ /// The CLI writes Windows paths with '/' separators.
+ 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);
+ }
+}
diff --git a/tests/HashTool.Cli.Tests/HashTool.Cli.Tests.csproj b/tests/HashTool.Cli.Tests/HashTool.Cli.Tests.csproj
new file mode 100644
index 0000000..7158245
--- /dev/null
+++ b/tests/HashTool.Cli.Tests/HashTool.Cli.Tests.csproj
@@ -0,0 +1,20 @@
+
+
+ Exe
+ false
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+