From 4bd17a50f4f640d8596e15e110f986a68d249c37 Mon Sep 17 00:00:00 2001 From: poli0981 <127664709+poli0981@users.noreply.github.com> Date: Thu, 15 Oct 2026 12:20:49 +0700 Subject: [PATCH] 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 --- HashTool.slnx | 6 + .../HashTool.Benchmarks.csproj | 16 ++ .../HashTool.Benchmarks/HashingBenchmarks.cs | 128 +++++++++++ bench/HashTool.Benchmarks/Program.cs | 8 + build/linux/hashtool.png | Bin 0 -> 28843 bytes build/macos/Info.plist | 86 ++++++++ dotnet-tools.json | 27 +++ src/HashTool.Cli/HashCommand.cs | 189 ++++++++++++++++ src/HashTool.Cli/HashTool.Cli.csproj | 27 +++ src/HashTool.Cli/HashToolCommand.cs | 114 ++++++++++ src/HashTool.Cli/Program.cs | 9 + src/HashTool.Cli/VerifyCommand.cs | 167 ++++++++++++++ tests/Compat/LegacyClient/LegacyClient.csproj | 16 ++ tests/Compat/LegacyClient/Program.cs | 49 +++++ .../HashTool.App.Tests.csproj | 21 ++ tests/HashTool.App.Tests/LocalizationTests.cs | 181 +++++++++++++++ tests/HashTool.App.Tests/RepositoryFiles.cs | 55 +++++ tests/HashTool.App.Tests/TestApp.cs | 20 ++ tests/HashTool.App.Tests/UnitTests.cs | 113 ++++++++++ tests/HashTool.App.Tests/ViewTests.cs | 80 +++++++ tests/HashTool.Cli.Tests/CliTests.cs | 206 ++++++++++++++++++ .../HashTool.Cli.Tests.csproj | 20 ++ 22 files changed, 1538 insertions(+) create mode 100644 bench/HashTool.Benchmarks/HashTool.Benchmarks.csproj create mode 100644 bench/HashTool.Benchmarks/HashingBenchmarks.cs create mode 100644 bench/HashTool.Benchmarks/Program.cs create mode 100644 build/linux/hashtool.png create mode 100644 build/macos/Info.plist create mode 100644 dotnet-tools.json create mode 100644 src/HashTool.Cli/HashCommand.cs create mode 100644 src/HashTool.Cli/HashTool.Cli.csproj create mode 100644 src/HashTool.Cli/HashToolCommand.cs create mode 100644 src/HashTool.Cli/Program.cs create mode 100644 src/HashTool.Cli/VerifyCommand.cs create mode 100644 tests/Compat/LegacyClient/LegacyClient.csproj create mode 100644 tests/Compat/LegacyClient/Program.cs create mode 100644 tests/HashTool.App.Tests/HashTool.App.Tests.csproj create mode 100644 tests/HashTool.App.Tests/LocalizationTests.cs create mode 100644 tests/HashTool.App.Tests/RepositoryFiles.cs create mode 100644 tests/HashTool.App.Tests/TestApp.cs create mode 100644 tests/HashTool.App.Tests/UnitTests.cs create mode 100644 tests/HashTool.App.Tests/ViewTests.cs create mode 100644 tests/HashTool.Cli.Tests/CliTests.cs create mode 100644 tests/HashTool.Cli.Tests/HashTool.Cli.Tests.csproj 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 0000000000000000000000000000000000000000..7194e4117a816da84a6b0b2c94d07263fe3b5db0 GIT binary patch literal 28843 zcmbq)cQn<1{Qvu2*R{F!Dl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)@{|);OUOn=P%Rz&FaGa9JtYYEFqBlv08RYg*Cu|$ o|G)8j#3RAS{eS#m7bEaY%*zBY>9U=GA%qZpZDXwp4cqAd164SSO8@`> literal 0 HcmV?d00001 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 + + + + + + + + + + + + + + +