Files
HashTool/src/HashTool.Cli/HashToolCommand.cs
T
poli0981andClaude Opus 5.5 4bd17a50f4 feat: hashtool CLI, app tests, release packaging inputs and benchmarks
- src/HashTool.Cli: `hashtool hash | verify | check | algorithms` on top of
  Core, NativeAOT-ready (3.9 MB native binary), coreutils-style output and
  exit codes (0 ok, 1 failed/mismatch, 2 usage or unreadable checksum
  file); Windows paths are written with '/' so lines need no escaping.
- tests/HashTool.Cli.Tests: commands, formats and exit codes.
- tests/HashTool.App.Tests (Avalonia headless): every page in several
  languages including RTL, a folder create-and-verify flow, translation
  integrity (keys, placeholders, Languages.json/resx/project wiring,
  satellite assemblies, unused keys), system language detection, command
  line parsing and helpers.
- tests/Compat/LegacyClient: drives Velopack 0.0.1298 (the library inside
  Hash Tool 1.1.x) against new release files for the upgrade gate.
- build/macos/Info.plist keeps the 1.x bundle identity and adds "Open
  With" document types; build/linux/hashtool.png is the AppImage icon.
- bench/HashTool.Benchmarks (BenchmarkDotNet) and a tool manifest pinning
  vpk 1.2.161, nuget-license and CycloneDX.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:16:40 +07:00

115 lines
4.7 KiB
C#

using System;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Parsing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using HashTool.Core.Checksums;
using HashTool.Core.Hashing;
namespace HashTool.Cli;
/// <summary>
/// <c>hashtool</c>: compute and verify hashes from the command line. Exit codes follow coreutils' <c>sha256sum</c>:
/// 0 = success, 1 = a file failed or did not match, 2 = usage error or unreadable checksum file.
/// </summary>
public static class HashToolCommand
{
public const int Success = 0;
public const int Failure = 1;
public const int UsageError = 2;
public static Task<int> RunAsync(string[] args, TextWriter output, TextWriter error, CancellationToken cancellationToken = default)
{
var parseResult = Build(output, error).Parse(args);
if (parseResult.Errors.Count > 0)
{
// Short message and exit code 2, like coreutils, instead of the full help text.
foreach (var parseError in parseResult.Errors) error.WriteLine($"hashtool: {parseError.Message}");
error.WriteLine("Try 'hashtool --help' for more information.");
return Task.FromResult(UsageError);
}
return parseResult.InvokeAsync(new InvocationConfiguration { Output = output, Error = error }, cancellationToken);
}
internal static RootCommand Build(TextWriter output, TextWriter error)
{
var root = new RootCommand($"Hash Tool {Version} - compute and verify file hashes and checksum files (SHA256SUMS, .md5, .sfv...).");
root.Subcommands.Add(HashCommand.Create(output, error));
root.Subcommands.Add(VerifyCommand.Create(output, error));
root.Subcommands.Add(VerifyCommand.CreateCheck(output, error));
root.Subcommands.Add(CreateAlgorithmsCommand(output));
return root;
}
internal static string Version =>
typeof(HashToolCommand).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
/// <summary><c>-a sha256 -a md5</c> or <c>-a sha256,md5</c>; names as listed by <c>hashtool algorithms</c>.</summary>
internal static Option<HashType[]> AlgorithmOption(string description) => new("--algorithm", "-a")
{
Description = description,
HelpName = "name",
Arity = ArgumentArity.OneOrMore,
CustomParser = ParseAlgorithms
};
private static HashType[] ParseAlgorithms(ArgumentResult result)
{
var algorithms = new List<HashType>();
foreach (var token in result.Tokens)
{
foreach (var name in token.Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (HashAlgorithms.TryParse(name, out var algorithm)) algorithms.Add(algorithm);
else result.AddError($"Unknown algorithm '{name}'. Run 'hashtool algorithms' to list the supported ones.");
}
}
return [.. algorithms.Distinct()];
}
private static Command CreateAlgorithmsCommand(TextWriter output)
{
var command = new Command("algorithms", "List the supported hash algorithms.");
command.SetAction(_ =>
{
foreach (var algorithm in HashAlgorithms.All)
{
var note = algorithm.IsInsecure() ? " (not collision resistant; use for integrity checks only)" : "";
output.WriteLine($"{algorithm.ToString().ToLowerInvariant(),-10} {HashAlgorithms.HexLength(algorithm),3} hex digits{note}");
}
return Success;
});
return command;
}
internal static void ReportError(TextWriter error, string path, Exception exception) =>
error.WriteLine($"hashtool: {path}: {Describe(exception)}");
internal static string Describe(Exception exception) => exception switch
{
FileNotFoundException or DirectoryNotFoundException => "No such file or directory",
UnauthorizedAccessException => "Permission denied",
_ => exception.Message
};
/// <summary>
/// Path as written to checksum output: relative to <paramref name="relativeTo"/> when given, otherwise absolute. Windows
/// separators become '/', so lines need no GNU escaping and the files also work with coreutils.
/// </summary>
internal static string DisplayPath(string fullPath, string? relativeTo)
{
var path = relativeTo is null ? fullPath : Path.GetRelativePath(relativeTo, fullPath);
return Portable(path);
}
internal static string Portable(string path) => OperatingSystem.IsWindows() ? path.Replace('\\', '/') : path;
}