From 6fa745f57cd873cc42c4535bedd2c00cbd634958 Mon Sep 17 00:00:00 2001 From: Adam Hathcock Date: Sat, 21 Feb 2026 17:07:50 +0000 Subject: [PATCH] first pass --- Directory.Packages.props | 2 + README.md | 2 +- SharpCompress.sln | 7 + docs/CLI.md | 47 +++ src/SharpCompress.Cli/CliEnums.cs | 19 ++ src/SharpCompress.Cli/CommandBuilder.cs | 298 ++++++++++++++++++ src/SharpCompress.Cli/Formats/FormatModels.cs | 13 + .../Formats/FormatsInspector.cs | 34 ++ .../Inspection/ArchiveInspector.cs | 289 +++++++++++++++++ .../Inspection/InspectionModels.cs | 49 +++ .../Inspection/InspectionRequest.cs | 12 + .../Output/CliJsonSerializerContext.cs | 17 + .../Output/JsonOutputRenderer.cs | 28 ++ .../Output/TableOutputRenderer.cs | 162 ++++++++++ src/SharpCompress.Cli/Program.cs | 6 + .../SharpCompress.Cli.csproj | 23 ++ src/SharpCompress.Cli/packages.lock.json | 74 +++++ src/SharpCompress/SharpCompress.csproj | 6 + .../Cli/ArchiveInspectorTests.cs | 82 +++++ .../SharpCompress.Test.csproj | 3 + tests/SharpCompress.Test/packages.lock.json | 20 ++ 21 files changed, 1192 insertions(+), 1 deletion(-) create mode 100644 docs/CLI.md create mode 100644 src/SharpCompress.Cli/CliEnums.cs create mode 100644 src/SharpCompress.Cli/CommandBuilder.cs create mode 100644 src/SharpCompress.Cli/Formats/FormatModels.cs create mode 100644 src/SharpCompress.Cli/Formats/FormatsInspector.cs create mode 100644 src/SharpCompress.Cli/Inspection/ArchiveInspector.cs create mode 100644 src/SharpCompress.Cli/Inspection/InspectionModels.cs create mode 100644 src/SharpCompress.Cli/Inspection/InspectionRequest.cs create mode 100644 src/SharpCompress.Cli/Output/CliJsonSerializerContext.cs create mode 100644 src/SharpCompress.Cli/Output/JsonOutputRenderer.cs create mode 100644 src/SharpCompress.Cli/Output/TableOutputRenderer.cs create mode 100644 src/SharpCompress.Cli/Program.cs create mode 100644 src/SharpCompress.Cli/SharpCompress.Cli.csproj create mode 100644 src/SharpCompress.Cli/packages.lock.json create mode 100644 tests/SharpCompress.Test/Cli/ArchiveInspectorTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 8f8510d9..96977436 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,6 +9,8 @@ + + diff --git a/README.md b/README.md index 2bdb58d3..b618c90a 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ GitHub Actions Build - Post Issues on Github! -Check the [Supported Formats](docs/FORMATS.md) and [Basic Usage.](docs/USAGE.md) +Check the [Supported Formats](docs/FORMATS.md), [Basic Usage](docs/USAGE.md), and [CLI Usage](docs/CLI.md). ## Custom Compression Providers diff --git a/SharpCompress.sln b/SharpCompress.sln index af132f4c..11688216 100644 --- a/SharpCompress.sln +++ b/SharpCompress.sln @@ -9,6 +9,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0F0901FF EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharpCompress", "src\SharpCompress\SharpCompress.csproj", "{FD19DDD8-72B2-4024-8665-0D1F7A2AA998}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharpCompress.Cli", "src\SharpCompress.Cli\SharpCompress.Cli.csproj", "{C6A0DE31-32FB-4B65-AFE5-6FEA0C610B4F}" +EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharpCompress.Test", "tests\SharpCompress.Test\SharpCompress.Test.csproj", "{F2B1A1EB-0FA6-40D0-8908-E13247C7226F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "build", "build\build.csproj", "{D4D613CB-5E94-47FB-85BE-B8423D20C545}" @@ -38,6 +40,10 @@ Global {FD19DDD8-72B2-4024-8665-0D1F7A2AA998}.Debug|Any CPU.Build.0 = Debug|Any CPU {FD19DDD8-72B2-4024-8665-0D1F7A2AA998}.Release|Any CPU.ActiveCfg = Release|Any CPU {FD19DDD8-72B2-4024-8665-0D1F7A2AA998}.Release|Any CPU.Build.0 = Release|Any CPU + {C6A0DE31-32FB-4B65-AFE5-6FEA0C610B4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C6A0DE31-32FB-4B65-AFE5-6FEA0C610B4F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C6A0DE31-32FB-4B65-AFE5-6FEA0C610B4F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C6A0DE31-32FB-4B65-AFE5-6FEA0C610B4F}.Release|Any CPU.Build.0 = Release|Any CPU {F2B1A1EB-0FA6-40D0-8908-E13247C7226F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F2B1A1EB-0FA6-40D0-8908-E13247C7226F}.Debug|Any CPU.Build.0 = Debug|Any CPU {F2B1A1EB-0FA6-40D0-8908-E13247C7226F}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -56,6 +62,7 @@ Global EndGlobalSection GlobalSection(NestedProjects) = preSolution {FD19DDD8-72B2-4024-8665-0D1F7A2AA998} = {3C5BE746-03E5-4895-9988-0B57F162F86C} + {C6A0DE31-32FB-4B65-AFE5-6FEA0C610B4F} = {3C5BE746-03E5-4895-9988-0B57F162F86C} {F2B1A1EB-0FA6-40D0-8908-E13247C7226F} = {0F0901FF-E8D9-426A-B5A2-17C7F47C1529} {5BDE6DBC-9E5F-4E21-AB71-F138A3E72B17} = {0F0901FF-E8D9-426A-B5A2-17C7F47C1529} EndGlobalSection diff --git a/docs/CLI.md b/docs/CLI.md new file mode 100644 index 00000000..620b3a8a --- /dev/null +++ b/docs/CLI.md @@ -0,0 +1,47 @@ +# SharpCompress CLI (Native AOT) + +`SharpCompress.Cli` is a `net10.0` console executable that inspects archives using SharpCompress APIs. + +## Build + +```bash +dotnet build src/SharpCompress.Cli/SharpCompress.Cli.csproj -c Release +``` + +## Run + +```bash +dotnet run --project src/SharpCompress.Cli/SharpCompress.Cli.csproj -- inspect tests/TestArchives/Archives/Zip.deflate.zip +``` + +## Commands + +- `inspect `: show archive summary and entry metadata. +- `list `: list entry metadata without summary. +- `formats`: list supported formats and whether they support forward or seekable mode. + +The root command also accepts archive paths directly and behaves like `inspect`. + +## Access Modes + +- `--access forward` (default): start with the forward-only Reader API. +- `--access seekable`: force Archive API mode. + +When `--access forward` is used, the CLI automatically switches to seekable mode when required (for example multi-volume archives). + +## Options + +- `--format table|json`: output mode. +- `--long`: include extra metadata columns. +- `--include-directories`: include directory entries in output. +- `--limit `: cap displayed entries per archive. +- `--password `: provide password for encrypted archives. +- `--look-for-header`: enable header scan for self-extracting archives. +- `--extension-hint `: help decoder selection (`zip`, `tar.gz`, `7z`, ...). +- `--rewindable-buffer-size `: tune forward detection buffering. + +## Native AOT Publish + +```bash +dotnet publish src/SharpCompress.Cli/SharpCompress.Cli.csproj -c Release -r osx-arm64 -p:PublishAot=true +``` diff --git a/src/SharpCompress.Cli/CliEnums.cs b/src/SharpCompress.Cli/CliEnums.cs new file mode 100644 index 00000000..866e4076 --- /dev/null +++ b/src/SharpCompress.Cli/CliEnums.cs @@ -0,0 +1,19 @@ +namespace SharpCompress.Cli; + +public enum AccessMode +{ + Forward, + Seekable, +} + +public enum OutputFormat +{ + Table, + Json, +} + +internal enum InspectionRenderMode +{ + Inspect, + List, +} diff --git a/src/SharpCompress.Cli/CommandBuilder.cs b/src/SharpCompress.Cli/CommandBuilder.cs new file mode 100644 index 00000000..6c26d8a4 --- /dev/null +++ b/src/SharpCompress.Cli/CommandBuilder.cs @@ -0,0 +1,298 @@ +using System; +using System.CommandLine; +using System.CommandLine.Parsing; +using SharpCompress.Cli.Formats; +using SharpCompress.Cli.Inspection; +using SharpCompress.Cli.Output; + +namespace SharpCompress.Cli; + +internal static class CommandBuilder +{ + public static RootCommand CreateRootCommand( + ArchiveInspector archiveInspector, + FormatsInspector formatsInspector + ) + { + var rootCommand = new RootCommand("Inspect archive files with SharpCompress."); + + var rootSymbols = CreateInspectionSymbols(); + AddInspectionSymbols(rootCommand, rootSymbols); + rootCommand.SetAction(parseResult => + ExecuteInspectionCommand( + parseResult, + rootSymbols, + archiveInspector, + InspectionRenderMode.Inspect + ) + ); + + rootCommand.Subcommands.Add(CreateInspectCommand(archiveInspector)); + rootCommand.Subcommands.Add(CreateListCommand(archiveInspector)); + rootCommand.Subcommands.Add(CreateFormatsCommand(formatsInspector)); + + return rootCommand; + } + + private static Command CreateInspectCommand(ArchiveInspector archiveInspector) + { + var command = new Command("inspect", "Inspect archives and print summary plus entries."); + var symbols = CreateInspectionSymbols(); + AddInspectionSymbols(command, symbols); + + command.SetAction(parseResult => + ExecuteInspectionCommand( + parseResult, + symbols, + archiveInspector, + InspectionRenderMode.Inspect + ) + ); + + return command; + } + + private static Command CreateListCommand(ArchiveInspector archiveInspector) + { + var command = new Command("list", "List archive entries."); + var symbols = CreateInspectionSymbols(); + AddInspectionSymbols(command, symbols); + + command.SetAction(parseResult => + ExecuteInspectionCommand( + parseResult, + symbols, + archiveInspector, + InspectionRenderMode.List + ) + ); + + return command; + } + + private static Command CreateFormatsCommand(FormatsInspector formatsInspector) + { + var command = new Command("formats", "List supported formats and access capabilities."); + var formatOption = CreateFormatOption(); + command.Options.Add(formatOption); + + command.SetAction(parseResult => + { + var outputFormat = ParseOutputFormat(parseResult.GetValue(formatOption)); + var formats = formatsInspector.GetFormats(); + if (outputFormat == OutputFormat.Json) + { + JsonOutputRenderer.RenderFormats(new FormatsReport(formats)); + } + else + { + TableOutputRenderer.RenderFormats(formats); + } + + return 0; + }); + + return command; + } + + private static int ExecuteInspectionCommand( + ParseResult parseResult, + InspectionSymbols symbols, + ArchiveInspector archiveInspector, + InspectionRenderMode renderMode + ) + { + var archives = parseResult.GetValue(symbols.ArchiveArgument) ?? []; + var request = new InspectionRequest + { + AccessMode = ParseAccessMode(parseResult.GetValue(symbols.AccessOption)), + Password = parseResult.GetValue(symbols.PasswordOption), + LookForHeader = parseResult.GetValue(symbols.LookForHeaderOption), + ExtensionHint = NormalizeExtensionHint( + parseResult.GetValue(symbols.ExtensionHintOption) + ), + RewindableBufferSize = parseResult.GetValue(symbols.RewindableBufferSizeOption), + IncludeDirectories = parseResult.GetValue(symbols.IncludeDirectoriesOption), + Limit = parseResult.GetValue(symbols.LimitOption), + }; + + var outputFormat = ParseOutputFormat(parseResult.GetValue(symbols.FormatOption)); + var longOutput = parseResult.GetValue(symbols.LongOption); + var report = archiveInspector.InspectArchives(archives, request); + + if (outputFormat == OutputFormat.Json) + { + JsonOutputRenderer.RenderInspectionReport(report); + } + else if (renderMode == InspectionRenderMode.List) + { + TableOutputRenderer.RenderList(report, longOutput); + } + else + { + TableOutputRenderer.RenderInspect(report, longOutput); + } + + return report.Errors.Count == 0 ? 0 : 1; + } + + private static InspectionSymbols CreateInspectionSymbols() + { + var archiveArgument = new Argument("archive") + { + Arity = ArgumentArity.OneOrMore, + Description = "Archive file paths to inspect.", + }; + + var accessOption = new Option("--access", "-a") + { + Description = "Access mode: forward or seekable.", + DefaultValueFactory = _ => "forward", + }; + accessOption.Validators.Add(result => + { + var access = result.GetValueOrDefault(); + if ( + !string.Equals(access, "forward", StringComparison.OrdinalIgnoreCase) + && !string.Equals(access, "seekable", StringComparison.OrdinalIgnoreCase) + ) + { + result.AddError("--access must be one of: forward, seekable."); + } + }); + + var formatOption = CreateFormatOption(); + + var longOption = new Option("--long", "-l") + { + Description = "Show additional entry metadata columns.", + }; + + var includeDirectoriesOption = new Option("--include-directories") + { + Description = "Include directory entries in output.", + }; + + var limitOption = new Option("--limit") + { + Description = "Maximum number of entries to print per archive.", + }; + limitOption.Validators.Add(result => + { + var limit = result.GetValueOrDefault(); + if (limit is <= 0) + { + result.AddError("--limit must be greater than zero."); + } + }); + + var passwordOption = new Option("--password") + { + Description = "Password for encrypted archives.", + }; + + var lookForHeaderOption = new Option("--look-for-header") + { + Description = "Enable header scanning for self-extracting archives.", + }; + + var extensionHintOption = new Option("--extension-hint") + { + Description = "Optional extension hint (for example: zip, tar.gz, 7z).", + }; + + var rewindableBufferSizeOption = new Option("--rewindable-buffer-size") + { + Description = "Rewindable buffer size for non-seekable stream detection.", + }; + rewindableBufferSizeOption.Validators.Add(result => + { + var size = result.GetValueOrDefault(); + if (size is <= 0) + { + result.AddError("--rewindable-buffer-size must be greater than zero."); + } + }); + + return new( + archiveArgument, + accessOption, + formatOption, + longOption, + includeDirectoriesOption, + limitOption, + passwordOption, + lookForHeaderOption, + extensionHintOption, + rewindableBufferSizeOption + ); + } + + private static Option CreateFormatOption() + { + var formatOption = new Option("--format", "-f") + { + Description = "Output format: table or json.", + DefaultValueFactory = _ => "table", + }; + formatOption.Validators.Add(result => + { + var output = result.GetValueOrDefault(); + if ( + !string.Equals(output, "table", StringComparison.OrdinalIgnoreCase) + && !string.Equals(output, "json", StringComparison.OrdinalIgnoreCase) + ) + { + result.AddError("--format must be one of: table, json."); + } + }); + return formatOption; + } + + private static void AddInspectionSymbols(Command command, InspectionSymbols symbols) + { + command.Arguments.Add(symbols.ArchiveArgument); + command.Options.Add(symbols.AccessOption); + command.Options.Add(symbols.FormatOption); + command.Options.Add(symbols.LongOption); + command.Options.Add(symbols.IncludeDirectoriesOption); + command.Options.Add(symbols.LimitOption); + command.Options.Add(symbols.PasswordOption); + command.Options.Add(symbols.LookForHeaderOption); + command.Options.Add(symbols.ExtensionHintOption); + command.Options.Add(symbols.RewindableBufferSizeOption); + } + + private static AccessMode ParseAccessMode(string? value) => + string.Equals(value, "seekable", StringComparison.OrdinalIgnoreCase) + ? AccessMode.Seekable + : AccessMode.Forward; + + private static OutputFormat ParseOutputFormat(string? value) => + string.Equals(value, "json", StringComparison.OrdinalIgnoreCase) + ? OutputFormat.Json + : OutputFormat.Table; + + private static string? NormalizeExtensionHint(string? extensionHint) + { + if (string.IsNullOrWhiteSpace(extensionHint)) + { + return null; + } + + return extensionHint.Trim().TrimStart('.'); + } + + private sealed record InspectionSymbols( + Argument ArchiveArgument, + Option AccessOption, + Option FormatOption, + Option LongOption, + Option IncludeDirectoriesOption, + Option LimitOption, + Option PasswordOption, + Option LookForHeaderOption, + Option ExtensionHintOption, + Option RewindableBufferSizeOption + ); +} diff --git a/src/SharpCompress.Cli/Formats/FormatModels.cs b/src/SharpCompress.Cli/Formats/FormatModels.cs new file mode 100644 index 00000000..7fc79922 --- /dev/null +++ b/src/SharpCompress.Cli/Formats/FormatModels.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; + +namespace SharpCompress.Cli.Formats; + +public sealed record FormatSupportResult( + string Name, + string ArchiveType, + List Extensions, + bool SupportsForward, + bool SupportsSeekable +); + +public sealed record FormatsReport(List Formats); diff --git a/src/SharpCompress.Cli/Formats/FormatsInspector.cs b/src/SharpCompress.Cli/Formats/FormatsInspector.cs new file mode 100644 index 00000000..d99989d8 --- /dev/null +++ b/src/SharpCompress.Cli/Formats/FormatsInspector.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; +using System.Linq; +using SharpCompress.Archives; +using SharpCompress.Factories; +using SharpCompress.Readers; + +namespace SharpCompress.Cli.Formats; + +public sealed class FormatsInspector +{ + public List GetFormats() + { + return Factory + .Factories.OfType() + .Select(factory => + { + var extensions = factory + .GetSupportedExtensions() + .Distinct() + .OrderBy(extension => extension) + .ToList(); + + return new FormatSupportResult( + Name: factory.Name, + ArchiveType: factory.KnownArchiveType?.ToString() ?? "Unknown", + Extensions: extensions, + SupportsForward: factory is IReaderFactory, + SupportsSeekable: factory is IArchiveFactory + ); + }) + .OrderBy(result => result.Name) + .ToList(); + } +} diff --git a/src/SharpCompress.Cli/Inspection/ArchiveInspector.cs b/src/SharpCompress.Cli/Inspection/ArchiveInspector.cs new file mode 100644 index 00000000..046ca8f5 --- /dev/null +++ b/src/SharpCompress.Cli/Inspection/ArchiveInspector.cs @@ -0,0 +1,289 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using SharpCompress.Archives; +using SharpCompress.Common; +using SharpCompress.Readers; + +namespace SharpCompress.Cli.Inspection; + +public sealed class ArchiveInspector +{ + public InspectionExecutionResult InspectArchives( + IEnumerable archivePaths, + InspectionRequest request + ) + { + ArgumentNullException.ThrowIfNull(archivePaths); + ArgumentNullException.ThrowIfNull(request); + + var archives = new List(); + var errors = new List(); + + foreach (var archivePath in archivePaths) + { + try + { + archives.Add(InspectArchive(archivePath, request)); + } + catch (Exception exception) + { + errors.Add(new InspectionError(archivePath, exception.Message)); + } + } + + return new InspectionExecutionResult(archives, errors); + } + + private static ArchiveInspectionResult InspectArchive( + string archivePath, + InspectionRequest request + ) + { + if (string.IsNullOrWhiteSpace(archivePath)) + { + throw new ArgumentException("Archive path is required.", nameof(archivePath)); + } + + var fileInfo = new FileInfo(archivePath); + if (!fileInfo.Exists) + { + throw new FileNotFoundException($"Archive file was not found: {fileInfo.FullName}"); + } + + var readerOptions = CreateReaderOptions(request); + var archiveParts = ArchiveFactory.GetFileParts(fileInfo).ToList(); + + if (request.AccessMode == AccessMode.Seekable) + { + return InspectWithSeekable( + fileInfo, + archiveParts, + readerOptions, + request, + autoFallbackApplied: false, + fallbackReason: null, + forcedSeekable: true + ); + } + + if (archiveParts.Count > 1) + { + return InspectWithSeekable( + fileInfo, + archiveParts, + readerOptions, + request, + autoFallbackApplied: true, + fallbackReason: "Detected multi-volume archive parts.", + forcedSeekable: false + ); + } + + try + { + return InspectWithForward(fileInfo, readerOptions, request); + } + catch (Exception exception) when (ShouldFallbackToSeekable(exception)) + { + return InspectWithSeekable( + fileInfo, + archiveParts, + readerOptions, + request, + autoFallbackApplied: true, + fallbackReason: $"Forward reader failed and seekable mode was used ({exception.GetType().Name}).", + forcedSeekable: false + ); + } + } + + private static ArchiveInspectionResult InspectWithForward( + FileInfo fileInfo, + ReaderOptions readerOptions, + InspectionRequest request + ) + { + using var reader = ReaderFactory.OpenReader(fileInfo, readerOptions); + var entries = new List(); + + var entryCount = 0; + var displayedEntryCount = 0; + var outputTruncated = false; + var totalCompressedSize = 0L; + var totalUncompressedSize = 0L; + var isSolid = false; + var isEncrypted = false; + + while (reader.MoveToNextEntry()) + { + var entry = reader.Entry; + entryCount++; + totalCompressedSize += entry.CompressedSize; + totalUncompressedSize += entry.Size; + isSolid |= entry.IsSolid; + isEncrypted |= entry.IsEncrypted; + + if (!ShouldIncludeEntry(entry, request)) + { + continue; + } + + if (request.Limit.HasValue && displayedEntryCount >= request.Limit.Value) + { + outputTruncated = true; + continue; + } + + entries.Add(MapEntry(entry)); + displayedEntryCount++; + } + + return new ArchiveInspectionResult( + ArchivePath: fileInfo.FullName, + ArchiveType: reader.ArchiveType.ToString(), + RequestedAccessMode: request.AccessMode, + UsedAccessMode: AccessMode.Forward, + AutoFallbackApplied: false, + FallbackReason: null, + IsComplete: null, + IsSolid: isSolid, + IsEncrypted: isEncrypted, + VolumeCount: 1, + EntryCount: entryCount, + DisplayedEntryCount: displayedEntryCount, + OutputTruncated: outputTruncated, + TotalCompressedSize: totalCompressedSize, + TotalUncompressedSize: totalUncompressedSize, + Entries: entries + ); + } + + private static ArchiveInspectionResult InspectWithSeekable( + FileInfo fileInfo, + List archiveParts, + ReaderOptions readerOptions, + InspectionRequest request, + bool autoFallbackApplied, + string? fallbackReason, + bool forcedSeekable + ) + { + try + { + using var archive = + archiveParts.Count == 1 + ? ArchiveFactory.OpenArchive(fileInfo, readerOptions) + : ArchiveFactory.OpenArchive(archiveParts, readerOptions); + + var entries = new List(); + var entryCount = 0; + var displayedEntryCount = 0; + var outputTruncated = false; + var totalCompressedSize = 0L; + var totalUncompressedSize = 0L; + + foreach (var entry in archive.Entries) + { + entryCount++; + totalCompressedSize += entry.CompressedSize; + totalUncompressedSize += entry.Size; + + if (!ShouldIncludeEntry(entry, request)) + { + continue; + } + + if (request.Limit.HasValue && displayedEntryCount >= request.Limit.Value) + { + outputTruncated = true; + continue; + } + + entries.Add(MapEntry(entry)); + displayedEntryCount++; + } + + return new ArchiveInspectionResult( + ArchivePath: fileInfo.FullName, + ArchiveType: archive.Type.ToString(), + RequestedAccessMode: request.AccessMode, + UsedAccessMode: AccessMode.Seekable, + AutoFallbackApplied: autoFallbackApplied, + FallbackReason: fallbackReason, + IsComplete: archive.IsComplete, + IsSolid: archive.IsSolid, + IsEncrypted: archive.IsEncrypted, + VolumeCount: archiveParts.Count, + EntryCount: entryCount, + DisplayedEntryCount: displayedEntryCount, + OutputTruncated: outputTruncated, + TotalCompressedSize: totalCompressedSize, + TotalUncompressedSize: totalUncompressedSize, + Entries: entries + ); + } + catch (Exception exception) + when (forcedSeekable && SupportsForwardOnly(fileInfo, readerOptions)) + { + throw new InvalidOperationException( + "Seekable mode is not available for this archive. Re-run the command with --access forward.", + exception + ); + } + } + + private static ReaderOptions CreateReaderOptions(InspectionRequest request) + { + var extensionHint = string.IsNullOrWhiteSpace(request.ExtensionHint) + ? null + : request.ExtensionHint; + + return ReaderOptions.ForOwnedFile with + { + Password = request.Password, + LookForHeader = request.LookForHeader, + ExtensionHint = extensionHint, + RewindableBufferSize = request.RewindableBufferSize, + }; + } + + private static bool ShouldFallbackToSeekable(Exception exception) => + exception is InvalidFormatException or ArchiveOperationException; + + private static bool SupportsForwardOnly(FileInfo fileInfo, ReaderOptions readerOptions) + { + try + { + using var reader = ReaderFactory.OpenReader(fileInfo, readerOptions); + return reader is not null; + } + catch + { + return false; + } + } + + private static bool ShouldIncludeEntry(IEntry entry, InspectionRequest request) => + request.IncludeDirectories || !entry.IsDirectory; + + private static ArchiveEntryResult MapEntry(IEntry entry) => + new( + Key: entry.Key ?? string.Empty, + CompressionType: entry.CompressionType, + CompressedSize: entry.CompressedSize, + Size: entry.Size, + IsDirectory: entry.IsDirectory, + IsEncrypted: entry.IsEncrypted, + IsSplitAfter: entry.IsSplitAfter, + IsSolid: entry.IsSolid, + VolumeIndexFirst: entry.VolumeIndexFirst, + VolumeIndexLast: entry.VolumeIndexLast, + LastModifiedTime: entry.LastModifiedTime, + CreatedTime: entry.CreatedTime, + LastAccessedTime: entry.LastAccessedTime, + ArchivedTime: entry.ArchivedTime, + LinkTarget: entry.LinkTarget + ); +} diff --git a/src/SharpCompress.Cli/Inspection/InspectionModels.cs b/src/SharpCompress.Cli/Inspection/InspectionModels.cs new file mode 100644 index 00000000..8fc49ddb --- /dev/null +++ b/src/SharpCompress.Cli/Inspection/InspectionModels.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using SharpCompress.Common; + +namespace SharpCompress.Cli.Inspection; + +public sealed record InspectionExecutionResult( + List Archives, + List Errors +); + +public sealed record ArchiveInspectionResult( + string ArchivePath, + string ArchiveType, + AccessMode RequestedAccessMode, + AccessMode UsedAccessMode, + bool AutoFallbackApplied, + string? FallbackReason, + bool? IsComplete, + bool IsSolid, + bool IsEncrypted, + int VolumeCount, + int EntryCount, + int DisplayedEntryCount, + bool OutputTruncated, + long TotalCompressedSize, + long TotalUncompressedSize, + List Entries +); + +public sealed record ArchiveEntryResult( + string Key, + CompressionType CompressionType, + long CompressedSize, + long Size, + bool IsDirectory, + bool IsEncrypted, + bool IsSplitAfter, + bool IsSolid, + int VolumeIndexFirst, + int VolumeIndexLast, + DateTime? LastModifiedTime, + DateTime? CreatedTime, + DateTime? LastAccessedTime, + DateTime? ArchivedTime, + string? LinkTarget +); + +public sealed record InspectionError(string ArchivePath, string Message); diff --git a/src/SharpCompress.Cli/Inspection/InspectionRequest.cs b/src/SharpCompress.Cli/Inspection/InspectionRequest.cs new file mode 100644 index 00000000..a481a696 --- /dev/null +++ b/src/SharpCompress.Cli/Inspection/InspectionRequest.cs @@ -0,0 +1,12 @@ +namespace SharpCompress.Cli.Inspection; + +public sealed record InspectionRequest +{ + public AccessMode AccessMode { get; init; } = AccessMode.Forward; + public string? Password { get; init; } + public bool LookForHeader { get; init; } + public string? ExtensionHint { get; init; } + public int? RewindableBufferSize { get; init; } + public bool IncludeDirectories { get; init; } + public int? Limit { get; init; } +} diff --git a/src/SharpCompress.Cli/Output/CliJsonSerializerContext.cs b/src/SharpCompress.Cli/Output/CliJsonSerializerContext.cs new file mode 100644 index 00000000..ad56b43e --- /dev/null +++ b/src/SharpCompress.Cli/Output/CliJsonSerializerContext.cs @@ -0,0 +1,17 @@ +using System.Text.Json.Serialization; +using SharpCompress.Cli.Formats; +using SharpCompress.Cli.Inspection; + +namespace SharpCompress.Cli.Output; + +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + WriteIndented = true +)] +[JsonSerializable(typeof(InspectionExecutionResult))] +[JsonSerializable(typeof(ArchiveInspectionResult))] +[JsonSerializable(typeof(ArchiveEntryResult))] +[JsonSerializable(typeof(InspectionError))] +[JsonSerializable(typeof(FormatsReport))] +[JsonSerializable(typeof(FormatSupportResult))] +internal sealed partial class CliJsonSerializerContext : JsonSerializerContext; diff --git a/src/SharpCompress.Cli/Output/JsonOutputRenderer.cs b/src/SharpCompress.Cli/Output/JsonOutputRenderer.cs new file mode 100644 index 00000000..d5136af2 --- /dev/null +++ b/src/SharpCompress.Cli/Output/JsonOutputRenderer.cs @@ -0,0 +1,28 @@ +using System; +using System.Text.Json; +using SharpCompress.Cli.Formats; +using SharpCompress.Cli.Inspection; + +namespace SharpCompress.Cli.Output; + +internal static class JsonOutputRenderer +{ + public static void RenderInspectionReport(InspectionExecutionResult report) + { + ArgumentNullException.ThrowIfNull(report); + + var json = JsonSerializer.Serialize( + report, + CliJsonSerializerContext.Default.InspectionExecutionResult + ); + Console.WriteLine(json); + } + + public static void RenderFormats(FormatsReport report) + { + ArgumentNullException.ThrowIfNull(report); + + var json = JsonSerializer.Serialize(report, CliJsonSerializerContext.Default.FormatsReport); + Console.WriteLine(json); + } +} diff --git a/src/SharpCompress.Cli/Output/TableOutputRenderer.cs b/src/SharpCompress.Cli/Output/TableOutputRenderer.cs new file mode 100644 index 00000000..7fb7d841 --- /dev/null +++ b/src/SharpCompress.Cli/Output/TableOutputRenderer.cs @@ -0,0 +1,162 @@ +using System; +using System.Globalization; +using SharpCompress.Cli.Formats; +using SharpCompress.Cli.Inspection; +using Spectre.Console; + +namespace SharpCompress.Cli.Output; + +internal static class TableOutputRenderer +{ + public static void RenderInspect(InspectionExecutionResult report, bool longOutput) + { + foreach (var archive in report.Archives) + { + AnsiConsole.Write(new Rule(Markup.Escape(archive.ArchivePath))); + RenderSummaryTable(archive); + RenderEntryTable(archive, longOutput); + AnsiConsole.WriteLine(); + } + + RenderErrors(report); + } + + public static void RenderList(InspectionExecutionResult report, bool longOutput) + { + foreach (var archive in report.Archives) + { + AnsiConsole.Write(new Rule(Markup.Escape(archive.ArchivePath))); + RenderEntryTable(archive, longOutput); + AnsiConsole.WriteLine(); + } + + RenderErrors(report); + } + + public static void RenderFormats( + System.Collections.Generic.IReadOnlyList formats + ) + { + var table = new Table().RoundedBorder(); + table.AddColumn("Format"); + table.AddColumn("ArchiveType"); + table.AddColumn("Extensions"); + table.AddColumn("Forward"); + table.AddColumn("Seekable"); + + foreach (var format in formats) + { + table.AddRow( + Markup.Escape(format.Name), + Markup.Escape(format.ArchiveType), + Markup.Escape(string.Join(", ", format.Extensions)), + format.SupportsForward ? "yes" : "no", + format.SupportsSeekable ? "yes" : "no" + ); + } + + AnsiConsole.Write(table); + } + + private static void RenderSummaryTable(ArchiveInspectionResult archive) + { + var table = new Table().RoundedBorder().HideHeaders(); + table.AddColumn("Key"); + table.AddColumn("Value"); + + table.AddRow("archive-type", Markup.Escape(archive.ArchiveType)); + table.AddRow("access-requested", archive.RequestedAccessMode.ToString().ToLowerInvariant()); + table.AddRow("access-used", archive.UsedAccessMode.ToString().ToLowerInvariant()); + table.AddRow("entries", archive.EntryCount.ToString(CultureInfo.InvariantCulture)); + table.AddRow( + "displayed", + archive.DisplayedEntryCount.ToString(CultureInfo.InvariantCulture) + ); + table.AddRow("volumes", archive.VolumeCount.ToString(CultureInfo.InvariantCulture)); + table.AddRow("compressed-size", FormatSize(archive.TotalCompressedSize)); + table.AddRow("uncompressed-size", FormatSize(archive.TotalUncompressedSize)); + table.AddRow("encrypted", archive.IsEncrypted ? "yes" : "no"); + table.AddRow("solid", archive.IsSolid ? "yes" : "no"); + if (archive.IsComplete.HasValue) + { + table.AddRow("complete", archive.IsComplete.Value ? "yes" : "no"); + } + if (archive.AutoFallbackApplied) + { + table.AddRow( + "fallback", + Markup.Escape(archive.FallbackReason ?? "seekable fallback applied") + ); + } + if (archive.OutputTruncated) + { + table.AddRow("truncated", "yes"); + } + + AnsiConsole.Write(table); + } + + private static void RenderEntryTable(ArchiveInspectionResult archive, bool longOutput) + { + var table = new Table().RoundedBorder(); + table.AddColumn("Entry"); + table.AddColumn("Compression"); + table.AddColumn("Size"); + table.AddColumn("Packed"); + table.AddColumn("Dir"); + table.AddColumn("Enc"); + + if (longOutput) + { + table.AddColumn("Modified"); + table.AddColumn("Split"); + table.AddColumn("Volumes"); + table.AddColumn("Link"); + } + + foreach (var entry in archive.Entries) + { + if (longOutput) + { + table.AddRow( + Markup.Escape(entry.Key), + Markup.Escape(entry.CompressionType.ToString()), + FormatSize(entry.Size), + FormatSize(entry.CompressedSize), + entry.IsDirectory ? "yes" : "no", + entry.IsEncrypted ? "yes" : "no", + entry.LastModifiedTime?.ToString("u", CultureInfo.InvariantCulture) ?? "", + entry.IsSplitAfter ? "yes" : "no", + $"{entry.VolumeIndexFirst}-{entry.VolumeIndexLast}", + Markup.Escape(entry.LinkTarget ?? string.Empty) + ); + } + else + { + table.AddRow( + Markup.Escape(entry.Key), + Markup.Escape(entry.CompressionType.ToString()), + FormatSize(entry.Size), + FormatSize(entry.CompressedSize), + entry.IsDirectory ? "yes" : "no", + entry.IsEncrypted ? "yes" : "no" + ); + } + } + + AnsiConsole.Write(table); + } + + private static void RenderErrors(InspectionExecutionResult report) + { + foreach (var error in report.Errors) + { + AnsiConsole.MarkupLine( + $"[red]error[/] {Markup.Escape(error.ArchivePath)}: {Markup.Escape(error.Message)}" + ); + } + } + + private static string FormatSize(long value) => + value.ToString("N0", CultureInfo.InvariantCulture); +} diff --git a/src/SharpCompress.Cli/Program.cs b/src/SharpCompress.Cli/Program.cs new file mode 100644 index 00000000..5ce836f3 --- /dev/null +++ b/src/SharpCompress.Cli/Program.cs @@ -0,0 +1,6 @@ +using SharpCompress.Cli; +using SharpCompress.Cli.Formats; +using SharpCompress.Cli.Inspection; + +var rootCommand = CommandBuilder.CreateRootCommand(new ArchiveInspector(), new FormatsInspector()); +return rootCommand.Parse(args).Invoke(); diff --git a/src/SharpCompress.Cli/SharpCompress.Cli.csproj b/src/SharpCompress.Cli/SharpCompress.Cli.csproj new file mode 100644 index 00000000..91ad6956 --- /dev/null +++ b/src/SharpCompress.Cli/SharpCompress.Cli.csproj @@ -0,0 +1,23 @@ + + + net10.0 + Exe + enable + ../../SharpCompress.snk + true + true + true + true + + + + + + + + + TargetFramework=net10.0;PublishAot=false;PublishTrimmed=false + + + + diff --git a/src/SharpCompress.Cli/packages.lock.json b/src/SharpCompress.Cli/packages.lock.json new file mode 100644 index 00000000..23dfe901 --- /dev/null +++ b/src/SharpCompress.Cli/packages.lock.json @@ -0,0 +1,74 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.DotNet.ILCompiler": { + "type": "Direct", + "requested": "[10.0.0, )", + "resolved": "10.0.0", + "contentHash": "f9u8fMRROe2lS5MOOLutK6iSNTK9pC3kqd90FIn8Sk29fbZ0QDjZrBbwUkhouk/8dppC71SIEQaag0lGRTxvfA==" + }, + "Microsoft.NET.ILLink.Tasks": { + "type": "Direct", + "requested": "[10.0.0, )", + "resolved": "10.0.0", + "contentHash": "kICGrGYEzCNI3wPzfEXcwNHgTvlvVn9yJDhSdRK+oZQy4jvYH529u7O0xf5ocQKzOMjfS07+3z9PKRIjrFMJDA==" + }, + "Microsoft.NETFramework.ReferenceAssemblies": { + "type": "Direct", + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", + "dependencies": { + "Microsoft.NETFramework.ReferenceAssemblies.net461": "1.0.3" + } + }, + "Microsoft.SourceLink.GitHub": { + "type": "Direct", + "requested": "[10.0.102, )", + "resolved": "10.0.102", + "contentHash": "Oxq3RCIJSdtpIU4hLqO7XaDe/Ra3HS9Wi8rJl838SAg6Zu1iQjerA0+xXWBgUFYbgknUGCLOU0T+lzMLkvY9Qg==", + "dependencies": { + "Microsoft.Build.Tasks.Git": "10.0.102", + "Microsoft.SourceLink.Common": "10.0.102" + } + }, + "Microsoft.VisualStudio.Threading.Analyzers": { + "type": "Direct", + "requested": "[17.14.15, )", + "resolved": "17.14.15", + "contentHash": "mXQPJsbuUD2ydq4/ffd8h8tSOFCXec+2xJOVNCvXjuMOq/+5EKHq3D2m2MC2+nUaXeFMSt66VS/J4HdKBixgcw==" + }, + "Spectre.Console": { + "type": "Direct", + "requested": "[0.54.0, )", + "resolved": "0.54.0", + "contentHash": "StDXCFayfy0yB1xzUHT2tgEpV1/HFTiS4JgsAQS49EYTfMixSwwucaQs/bIOCwXjWwIQTMuxjUIxcB5XsJkFJA==" + }, + "System.CommandLine": { + "type": "Direct", + "requested": "[2.0.3, )", + "resolved": "2.0.3", + "contentHash": "5nY9hlrGGFEmyecNUux58sohD2Q16U6jlFBYwH57b2IVUs+u7LfMFaHwOtw2tuIi8CUl6jKXw5s4FuIt9aLtug==" + }, + "Microsoft.Build.Tasks.Git": { + "type": "Transitive", + "resolved": "10.0.102", + "contentHash": "0i81LYX31U6UiXz4NOLbvc++u+/mVDmOt+PskrM/MygpDxkv9THKQyRUmavBpLK6iBV0abNWnn+CQgSRz//Pwg==" + }, + "Microsoft.NETFramework.ReferenceAssemblies.net461": { + "type": "Transitive", + "resolved": "1.0.3", + "contentHash": "AmOJZwCqnOCNp6PPcf9joyogScWLtwy0M1WkqfEQ0M9nYwyDD7EX9ZjscKS5iYnyvteX7kzSKFCKt9I9dXA6mA==" + }, + "Microsoft.SourceLink.Common": { + "type": "Transitive", + "resolved": "10.0.102", + "contentHash": "Mk1IMb9q5tahC2NltxYXFkLBtuBvfBoCQ3pIxYQWfzbCE9o1OB9SsHe0hnNGo7lWgTA/ePbFAJLWu6nLL9K17A==" + }, + "sharpcompress": { + "type": "Project" + } + } + } +} \ No newline at end of file diff --git a/src/SharpCompress/SharpCompress.csproj b/src/SharpCompress/SharpCompress.csproj index d3ccd21d..fd2568fc 100644 --- a/src/SharpCompress/SharpCompress.csproj +++ b/src/SharpCompress/SharpCompress.csproj @@ -27,9 +27,15 @@ true true $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + $(TreatAsLocalProperty);PublishAot;PublishTrimmed;RuntimeIdentifier;SelfContained + + + net10.0 $(DefineConstants);LEGACY_DOTNET + false + false true diff --git a/tests/SharpCompress.Test/Cli/ArchiveInspectorTests.cs b/tests/SharpCompress.Test/Cli/ArchiveInspectorTests.cs new file mode 100644 index 00000000..b1856fc3 --- /dev/null +++ b/tests/SharpCompress.Test/Cli/ArchiveInspectorTests.cs @@ -0,0 +1,82 @@ +#if NET10_0_OR_GREATER +using System.IO; +using SharpCompress.Cli; +using SharpCompress.Cli.Inspection; +using Xunit; + +namespace SharpCompress.Test.Cli; + +public class ArchiveInspectorTests : TestBase +{ + [Fact] + public void Forward_Default_UsesForward_ForSimpleZipArchive() + { + var inspector = new ArchiveInspector(); + var archivePath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.zip"); + + var result = inspector.InspectArchives([archivePath], new InspectionRequest()); + + Assert.Empty(result.Errors); + var archive = Assert.Single(result.Archives); + Assert.Equal(AccessMode.Forward, archive.RequestedAccessMode); + Assert.Equal(AccessMode.Forward, archive.UsedAccessMode); + Assert.False(archive.AutoFallbackApplied); + Assert.Null(archive.FallbackReason); + Assert.Equal("Zip", archive.ArchiveType); + Assert.True(archive.EntryCount > 0); + } + + [Fact] + public void Seekable_Mode_ForcesSeekable_ForSimpleZipArchive() + { + var inspector = new ArchiveInspector(); + var archivePath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.zip"); + + var result = inspector.InspectArchives( + [archivePath], + new InspectionRequest { AccessMode = AccessMode.Seekable } + ); + + Assert.Empty(result.Errors); + var archive = Assert.Single(result.Archives); + Assert.Equal(AccessMode.Seekable, archive.RequestedAccessMode); + Assert.Equal(AccessMode.Seekable, archive.UsedAccessMode); + Assert.False(archive.AutoFallbackApplied); + Assert.True(archive.IsComplete); + } + + [Fact] + public void Forward_Default_FallsBackToSeekable_ForSplitZipArchive() + { + var inspector = new ArchiveInspector(); + var archivePath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.split.001"); + + var result = inspector.InspectArchives([archivePath], new InspectionRequest()); + + Assert.Empty(result.Errors); + var archive = Assert.Single(result.Archives); + Assert.Equal(AccessMode.Forward, archive.RequestedAccessMode); + Assert.Equal(AccessMode.Seekable, archive.UsedAccessMode); + Assert.True(archive.AutoFallbackApplied); + Assert.Contains("multi-volume", archive.FallbackReason); + Assert.True(archive.VolumeCount > 1); + } + + [Fact] + public void Seekable_Mode_ShowsActionableError_ForForwardOnlyArchive() + { + var inspector = new ArchiveInspector(); + var archivePath = Path.Combine(TEST_ARCHIVES_PATH, "Ace.method1.ace"); + + var result = inspector.InspectArchives( + [archivePath], + new InspectionRequest { AccessMode = AccessMode.Seekable } + ); + + Assert.Empty(result.Archives); + var error = Assert.Single(result.Errors); + Assert.Equal(archivePath, error.ArchivePath); + Assert.Contains("--access forward", error.Message); + } +} +#endif diff --git a/tests/SharpCompress.Test/SharpCompress.Test.csproj b/tests/SharpCompress.Test/SharpCompress.Test.csproj index 9d56d13f..46f468ed 100644 --- a/tests/SharpCompress.Test/SharpCompress.Test.csproj +++ b/tests/SharpCompress.Test/SharpCompress.Test.csproj @@ -19,6 +19,9 @@ + + + diff --git a/tests/SharpCompress.Test/packages.lock.json b/tests/SharpCompress.Test/packages.lock.json index 2d35029e..cbd3ad31 100644 --- a/tests/SharpCompress.Test/packages.lock.json +++ b/tests/SharpCompress.Test/packages.lock.json @@ -525,11 +525,31 @@ "sharpcompress": { "type": "Project" }, + "sharpcompress.cli": { + "type": "Project", + "dependencies": { + "SharpCompress": "[0.0.0, )", + "Spectre.Console": "[0.54.0, )", + "System.CommandLine": "[2.0.3, )" + } + }, "Microsoft.Bcl.AsyncInterfaces": { "type": "CentralTransitive", "requested": "[10.0.0, )", "resolved": "10.0.0", "contentHash": "vFuwSLj9QJBbNR0NeNO4YVASUbokxs+i/xbuu8B+Fs4FAZg5QaFa6eGrMaRqTzzNI5tAb97T7BhSxtLckFyiRA==" + }, + "Spectre.Console": { + "type": "CentralTransitive", + "requested": "[0.54.0, )", + "resolved": "0.54.0", + "contentHash": "StDXCFayfy0yB1xzUHT2tgEpV1/HFTiS4JgsAQS49EYTfMixSwwucaQs/bIOCwXjWwIQTMuxjUIxcB5XsJkFJA==" + }, + "System.CommandLine": { + "type": "CentralTransitive", + "requested": "[2.0.3, )", + "resolved": "2.0.3", + "contentHash": "5nY9hlrGGFEmyecNUux58sohD2Q16U6jlFBYwH57b2IVUs+u7LfMFaHwOtw2tuIi8CUl6jKXw5s4FuIt9aLtug==" } } }