first pass

This commit is contained in:
Adam Hathcock
2026-02-21 17:07:50 +00:00
parent a8545ffb67
commit 6fa745f57c
21 changed files with 1192 additions and 1 deletions

View File

@@ -9,6 +9,8 @@
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageVersion Include="Mono.Posix.NETStandard" Version="1.0.0" />
<PackageVersion Include="SimpleExec" Version="13.0.0" />
<PackageVersion Include="Spectre.Console" Version="0.54.0" />
<PackageVersion Include="System.CommandLine" Version="2.0.3" />
<PackageVersion Include="System.Text.Encoding.CodePages" Version="10.0.0" />
<PackageVersion Include="System.Buffers" Version="4.6.1" />
<PackageVersion Include="System.Memory" Version="4.6.3" />

View File

@@ -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

View File

@@ -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

47
docs/CLI.md Normal file
View File

@@ -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 <archive...>`: show archive summary and entry metadata.
- `list <archive...>`: 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 <n>`: cap displayed entries per archive.
- `--password <value>`: provide password for encrypted archives.
- `--look-for-header`: enable header scan for self-extracting archives.
- `--extension-hint <ext>`: help decoder selection (`zip`, `tar.gz`, `7z`, ...).
- `--rewindable-buffer-size <bytes>`: tune forward detection buffering.
## Native AOT Publish
```bash
dotnet publish src/SharpCompress.Cli/SharpCompress.Cli.csproj -c Release -r osx-arm64 -p:PublishAot=true
```

View File

@@ -0,0 +1,19 @@
namespace SharpCompress.Cli;
public enum AccessMode
{
Forward,
Seekable,
}
public enum OutputFormat
{
Table,
Json,
}
internal enum InspectionRenderMode
{
Inspect,
List,
}

View File

@@ -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<string[]>("archive")
{
Arity = ArgumentArity.OneOrMore,
Description = "Archive file paths to inspect.",
};
var accessOption = new Option<string>("--access", "-a")
{
Description = "Access mode: forward or seekable.",
DefaultValueFactory = _ => "forward",
};
accessOption.Validators.Add(result =>
{
var access = result.GetValueOrDefault<string>();
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<bool>("--long", "-l")
{
Description = "Show additional entry metadata columns.",
};
var includeDirectoriesOption = new Option<bool>("--include-directories")
{
Description = "Include directory entries in output.",
};
var limitOption = new Option<int?>("--limit")
{
Description = "Maximum number of entries to print per archive.",
};
limitOption.Validators.Add(result =>
{
var limit = result.GetValueOrDefault<int?>();
if (limit is <= 0)
{
result.AddError("--limit must be greater than zero.");
}
});
var passwordOption = new Option<string?>("--password")
{
Description = "Password for encrypted archives.",
};
var lookForHeaderOption = new Option<bool>("--look-for-header")
{
Description = "Enable header scanning for self-extracting archives.",
};
var extensionHintOption = new Option<string?>("--extension-hint")
{
Description = "Optional extension hint (for example: zip, tar.gz, 7z).",
};
var rewindableBufferSizeOption = new Option<int?>("--rewindable-buffer-size")
{
Description = "Rewindable buffer size for non-seekable stream detection.",
};
rewindableBufferSizeOption.Validators.Add(result =>
{
var size = result.GetValueOrDefault<int?>();
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<string> CreateFormatOption()
{
var formatOption = new Option<string>("--format", "-f")
{
Description = "Output format: table or json.",
DefaultValueFactory = _ => "table",
};
formatOption.Validators.Add(result =>
{
var output = result.GetValueOrDefault<string>();
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<string[]> ArchiveArgument,
Option<string> AccessOption,
Option<string> FormatOption,
Option<bool> LongOption,
Option<bool> IncludeDirectoriesOption,
Option<int?> LimitOption,
Option<string?> PasswordOption,
Option<bool> LookForHeaderOption,
Option<string?> ExtensionHintOption,
Option<int?> RewindableBufferSizeOption
);
}

View File

@@ -0,0 +1,13 @@
using System.Collections.Generic;
namespace SharpCompress.Cli.Formats;
public sealed record FormatSupportResult(
string Name,
string ArchiveType,
List<string> Extensions,
bool SupportsForward,
bool SupportsSeekable
);
public sealed record FormatsReport(List<FormatSupportResult> Formats);

View File

@@ -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<FormatSupportResult> GetFormats()
{
return Factory
.Factories.OfType<IFactory>()
.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();
}
}

View File

@@ -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<string> archivePaths,
InspectionRequest request
)
{
ArgumentNullException.ThrowIfNull(archivePaths);
ArgumentNullException.ThrowIfNull(request);
var archives = new List<ArchiveInspectionResult>();
var errors = new List<InspectionError>();
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<ArchiveEntryResult>();
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<FileInfo> 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<ArchiveEntryResult>();
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
);
}

View File

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using SharpCompress.Common;
namespace SharpCompress.Cli.Inspection;
public sealed record InspectionExecutionResult(
List<ArchiveInspectionResult> Archives,
List<InspectionError> 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<ArchiveEntryResult> 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);

View File

@@ -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; }
}

View File

@@ -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;

View File

@@ -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);
}
}

View File

@@ -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<FormatSupportResult> 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);
}

View File

@@ -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();

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyOriginatorKeyFile>../../SharpCompress.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<PublishAot>true</PublishAot>
<PublishTrimmed>true</PublishTrimmed>
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Spectre.Console" />
<PackageReference Include="System.CommandLine" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SharpCompress\SharpCompress.csproj">
<AdditionalProperties>
TargetFramework=net10.0;PublishAot=false;PublishTrimmed=false
</AdditionalProperties>
</ProjectReference>
</ItemGroup>
</Project>

View File

@@ -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"
}
}
}
}

View File

@@ -27,9 +27,15 @@
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<TreatAsLocalProperty>$(TreatAsLocalProperty);PublishAot;PublishTrimmed;RuntimeIdentifier;SelfContained</TreatAsLocalProperty>
</PropertyGroup>
<PropertyGroup Condition="'$(PublishAot)' == 'true'">
<TargetFrameworks>net10.0</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'net48' Or '$(TargetFramework)' == 'netstandard2.0' ">
<DefineConstants>$(DefineConstants);LEGACY_DOTNET</DefineConstants>
<PublishAot>false</PublishAot>
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'net8.0' Or '$(TargetFramework)' == 'net10.0' ">
<IsTrimmable>true</IsTrimmable>

View File

@@ -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

View File

@@ -19,6 +19,9 @@
<ItemGroup>
<ProjectReference Include="..\..\src\SharpCompress\SharpCompress.csproj" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net10.0' ">
<ProjectReference Include="..\..\src\SharpCompress.Cli\SharpCompress.Cli.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AwesomeAssertions" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />

View File

@@ -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=="
}
}
}