From 740ae8fa89ee3f6d2c84e75023c97e20ebac21ad Mon Sep 17 00:00:00 2001 From: Adam Hathcock Date: Wed, 21 Oct 2026 08:42:00 +0100 Subject: [PATCH] Refactor factory workflows into internal Pure.DI services --- Directory.Packages.props | 1 + docs/ARCHITECTURE.md | 15 + src/SharpCompress/Archives/ArchiveFactory.cs | 321 +++++++++--------- .../Archives/IArchiveEntryExtensions.cs | 74 +--- src/SharpCompress/Readers/ReaderFactory.cs | 101 ++---- .../Services/ArchiveExtractor.cs | 80 +++++ .../Services/ArchiveFileWriter.cs | 92 +++++ .../ArchiveService.Async.cs} | 15 +- .../ArchiveService.Detection.Async.cs} | 37 +- .../ArchiveService.Detection.cs} | 5 +- .../ArchiveService.Information.Async.cs} | 23 +- .../ArchiveService.Information.cs} | 7 +- src/SharpCompress/Services/ArchiveService.cs | 227 +++++++++++++ src/SharpCompress/Services/FactoryCatalog.cs | 15 + .../ReaderService.Async.cs} | 13 +- src/SharpCompress/Services/ReaderService.cs | 89 +++++ .../Services/ServiceComposition.cs | 40 +++ src/SharpCompress/Services/WriterService.cs | 120 +++++++ src/SharpCompress/SharpCompress.csproj | 1 + .../Writers/IWriterExtensions.cs | 83 ++--- src/SharpCompress/Writers/WriterFactory.cs | 120 ++----- src/SharpCompress/packages.lock.json | 36 ++ .../ServiceCompositionTests.cs | 293 ++++++++++++++++ 23 files changed, 1314 insertions(+), 494 deletions(-) create mode 100644 src/SharpCompress/Services/ArchiveExtractor.cs create mode 100644 src/SharpCompress/Services/ArchiveFileWriter.cs rename src/SharpCompress/{Archives/ArchiveFactory.Async.cs => Services/ArchiveService.Async.cs} (89%) rename src/SharpCompress/{Archives/ArchiveFactory.Detection.Async.cs => Services/ArchiveService.Detection.Async.cs} (91%) rename src/SharpCompress/{Archives/ArchiveFactory.Detection.cs => Services/ArchiveService.Detection.cs} (92%) rename src/SharpCompress/{Archives/ArchiveFactory.Information.Async.cs => Services/ArchiveService.Information.Async.cs} (96%) rename src/SharpCompress/{Archives/ArchiveFactory.Information.cs => Services/ArchiveService.Information.cs} (98%) create mode 100644 src/SharpCompress/Services/ArchiveService.cs create mode 100644 src/SharpCompress/Services/FactoryCatalog.cs rename src/SharpCompress/{Readers/ReaderFactory.Async.cs => Services/ReaderService.Async.cs} (91%) create mode 100644 src/SharpCompress/Services/ReaderService.cs create mode 100644 src/SharpCompress/Services/ServiceComposition.cs create mode 100644 src/SharpCompress/Services/WriterService.cs create mode 100644 tests/SharpCompress.Test/ServiceCompositionTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index b9457b1d..2cdda454 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -8,6 +8,7 @@ + diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c463bf8e..ce97e44a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -136,6 +136,21 @@ Stream wrappers and utilities. ## Design Patterns +### Internal Service Composition + +The public static factories delegate to internal instance services assembled by Pure.DI in +`src/SharpCompress/Services/ServiceComposition.cs` in the `SharpCompress.Services` namespace. +Pure.DI is a private build-time dependency; consumers +do not need a container or a new client API. The default graph reuses workflow services, not +opened archives, readers, writers, or streams, which retain their existing ownership rules. +Services are exposed directly as typed composition roots, each a singleton within its composition. + +An injected `FactoryCatalog` supplies factories and TAR wrappers. The default catalog reads +through to `Factory.Factories` and the existing `TarWrapper.Wrappers` array rather than freezing +them at composition time, so late `Factory.RegisterFactory` calls continue to work. Tests can +compose independent graphs with their own catalogs without changing global registrations. +Compression providers still come from each operation's existing reader/writer options. + ### 1. Factory Pattern **Purpose:** Auto-detect format and create appropriate reader/writer. diff --git a/src/SharpCompress/Archives/ArchiveFactory.cs b/src/SharpCompress/Archives/ArchiveFactory.cs index efff5604..425dbc87 100644 --- a/src/SharpCompress/Archives/ArchiveFactory.cs +++ b/src/SharpCompress/Archives/ArchiveFactory.cs @@ -1,233 +1,222 @@ -using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Threading; using System.Threading.Tasks; using SharpCompress.Common; using SharpCompress.Common.Options; +using SharpCompress.Detection; using SharpCompress.Factories; using SharpCompress.Readers; +using SharpCompress.Services; namespace SharpCompress.Archives; public static partial class ArchiveFactory { - public static IArchive OpenArchive(Stream stream, ReaderOptions? readerOptions = null) - { - readerOptions ??= ReaderOptions.ForExternalStream; - return FindFactory(stream, readerOptions) - .OpenArchive(stream, readerOptions); - } + private static ArchiveService Service => LibraryDefaults.Composition.Archives; - public static IWritableArchive CreateArchive() - where TOptions : IWriterOptions - { - var factory = Factory - .Factories.OfType>() - .FirstOrDefault(); + public static IArchive OpenArchive(Stream stream, ReaderOptions? readerOptions = null) => + Service.OpenArchive(stream, readerOptions); - if (factory != null) - { - return factory.CreateArchive(); - } + public static IArchive OpenArchive(string filePath, ReaderOptions? options = null) => + Service.OpenArchive(filePath, options); - throw new NotSupportedException("Cannot create Archives of type: " + typeof(TOptions)); - } - - public static IArchive OpenArchive(string filePath, ReaderOptions? options = null) - { - filePath.NotNullOrEmpty(nameof(filePath)); - return OpenArchive(new FileInfo(filePath), options ?? ReaderOptions.ForFilePath); - } - - public static IArchive OpenArchive(FileInfo fileInfo, ReaderOptions? options = null) - { - options ??= ReaderOptions.ForFilePath; - - return FindFactory(fileInfo, options).OpenArchive(fileInfo, options); - } + public static IArchive OpenArchive(FileInfo fileInfo, ReaderOptions? options = null) => + Service.OpenArchive(fileInfo, options); public static IArchive OpenArchive( IReadOnlyList fileInfos, ReaderOptions? options = null - ) - { - fileInfos.NotNull(nameof(fileInfos)); - var filesArray = fileInfos; - if (filesArray.Count == 0) - { - throw new ArchiveOperationException("No files to open"); - } + ) => Service.OpenArchive(fileInfos, options); - var fileInfo = filesArray[0]; - if (filesArray.Count == 1) - { - return OpenArchive(fileInfo, options); - } + public static IArchive OpenArchive( + IReadOnlyList streams, + ReaderOptions? options = null + ) => Service.OpenArchive(streams, options); - fileInfo.NotNull(nameof(fileInfo)); - options ??= ReaderOptions.ForFilePath; + public static IWritableArchive CreateArchive() + where TOptions : IWriterOptions => Service.CreateArchive(); - return FindFactory(fileInfo, options) - .OpenArchive(filesArray, options); - } + public static ValueTask OpenAsyncArchive( + Stream stream, + ReaderOptions? readerOptions = null, + CancellationToken cancellationToken = default + ) => Service.OpenAsyncArchive(stream, readerOptions, cancellationToken); - public static IArchive OpenArchive(IReadOnlyList streams, ReaderOptions? options = null) - { - var streamsArray = streams.RequireReadable().RequireSeekable().ToList(); - if (streamsArray.Count == 0) - { - throw new ArchiveOperationException("No streams"); - } + public static ValueTask OpenAsyncArchive( + string filePath, + ReaderOptions? options = null, + CancellationToken cancellationToken = default + ) => Service.OpenAsyncArchive(filePath, options, cancellationToken); - var firstStream = streamsArray[0]; - if (streamsArray.Count == 1) - { - return OpenArchive(firstStream, options); - } + public static ValueTask OpenAsyncArchive( + FileInfo fileInfo, + ReaderOptions? options = null, + CancellationToken cancellationToken = default + ) => Service.OpenAsyncArchive(fileInfo, options, cancellationToken); - firstStream.NotNull(nameof(firstStream)); - options ??= ReaderOptions.ForExternalStream; + public static ValueTask OpenAsyncArchive( + IReadOnlyList fileInfos, + ReaderOptions? options = null, + CancellationToken cancellationToken = default + ) => Service.OpenAsyncArchive(fileInfos, options, cancellationToken); - return FindFactory(firstStream, options) - .OpenArchive(streamsArray, options); - } + public static ValueTask OpenAsyncArchive( + IReadOnlyList streams, + ReaderOptions? options = null, + CancellationToken cancellationToken = default + ) => Service.OpenAsyncArchive(streams, options, cancellationToken); public static void WriteToDirectory( string sourceArchive, string destinationDirectory, ExtractionOptions? options = null - ) - { - using var archive = OpenArchive(sourceArchive); - archive.WriteToDirectory(destinationDirectory, options); - } + ) => Service.WriteToDirectory(sourceArchive, destinationDirectory, options); public static T FindFactory(string filePath) - where T : IFactory - { - filePath.NotNullOrEmpty(nameof(filePath)); - using Stream stream = File.OpenRead(filePath); - return FindFactory(stream); - } + where T : IFactory => Service.FindFactory(filePath); public static T FindFactory(FileInfo finfo) - where T : IFactory - { - finfo.NotNull(nameof(finfo)); - using Stream stream = finfo.OpenRead(); - return FindFactory(stream); - } + where T : IFactory => Service.FindFactory(finfo); public static T FindFactory(Stream stream) - where T : IFactory => FindFactory(stream, ReaderOptions.ForExternalStream); + where T : IFactory => Service.FindFactory(stream); - public static bool IsArchive(string filePath, out ArchiveType? type) - { - return IsArchive(filePath, ReaderOptions.ForFilePath, out type); - } + internal static ValueTask FindFactoryAsync( + string filePath, + CancellationToken cancellationToken = default + ) + where T : IFactory => Service.FindFactoryAsync(filePath, cancellationToken); + + internal static ValueTask FindFactoryAsync( + FileInfo fileInfo, + CancellationToken cancellationToken = default + ) + where T : IFactory => Service.FindFactoryAsync(fileInfo, cancellationToken); + + internal static ValueTask FindFactoryAsync( + Stream stream, + CancellationToken cancellationToken = default + ) + where T : IFactory => Service.FindFactoryAsync(stream, cancellationToken); + + public static bool IsArchive(string filePath, out ArchiveType? type) => + Service.IsArchive(filePath, out type); public static bool IsArchive( string filePath, ReaderOptions? readerOptions, out ArchiveType? type - ) - { - filePath.NotNullOrEmpty(nameof(filePath)); - using Stream s = File.OpenRead(filePath); - return IsArchive(s, readerOptions ?? ReaderOptions.ForFilePath, out type); - } + ) => Service.IsArchive(filePath, readerOptions, out type); - public static bool IsArchive(Stream stream, out ArchiveType? type) - { - return IsArchive(stream, ReaderOptions.ForExternalStream, out type); - } + public static bool IsArchive(Stream stream, out ArchiveType? type) => + Service.IsArchive(stream, out type); - public static bool IsArchive(Stream stream, ReaderOptions? readerOptions, out ArchiveType? type) - { - stream.RequireReadable(); - stream.RequireSeekable(); + public static bool IsArchive( + Stream stream, + ReaderOptions? readerOptions, + out ArchiveType? type + ) => Service.IsArchive(stream, readerOptions, out type); - var factory = TryFindFactory(stream, readerOptions ?? ReaderOptions.ForExternalStream); - type = factory?.KnownArchiveType; - return factory is not null; - } - - public static async ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( + public static ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( string filePath, CancellationToken cancellationToken = default - ) => - await IsArchiveAsync(filePath, ReaderOptions.ForFilePath, cancellationToken) - .ConfigureAwait(false); + ) => Service.IsArchiveAsync(filePath, cancellationToken); - public static async ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( + public static ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( string filePath, ReaderOptions? readerOptions, CancellationToken cancellationToken = default - ) - { - filePath.NotNullOrEmpty(nameof(filePath)); - using Stream stream = File.OpenRead(filePath); - return await IsArchiveAsync( - stream, - readerOptions ?? ReaderOptions.ForFilePath, - cancellationToken - ) - .ConfigureAwait(false); - } + ) => Service.IsArchiveAsync(filePath, readerOptions, cancellationToken); - public static async ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( + public static ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( Stream stream, CancellationToken cancellationToken = default - ) => - await IsArchiveAsync(stream, ReaderOptions.ForExternalStream, cancellationToken) - .ConfigureAwait(false); + ) => Service.IsArchiveAsync(stream, cancellationToken); - public static async ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( + public static ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( Stream stream, ReaderOptions? readerOptions, CancellationToken cancellationToken = default - ) - { - stream.RequireReadable(); - stream.RequireSeekable(); + ) => Service.IsArchiveAsync(stream, readerOptions, cancellationToken); - var factory = await TryFindFactoryAsync( - stream, - readerOptions ?? ReaderOptions.ForExternalStream, - cancellationToken - ) - .ConfigureAwait(false); - return (factory is not null, factory?.KnownArchiveType); - } + /// Identify the archive without enumerating its entries. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask DetectArchiveAsync( + string filePath, + CancellationToken cancellationToken = default + ) => Service.DetectArchiveAsync(filePath, cancellationToken); - public static IEnumerable GetFileParts(string part1) - { - part1.NotNullOrEmpty(nameof(part1)); - return GetFileParts(new FileInfo(part1)).Select(a => a.FullName); - } + /// Identify the archive without enumerating its entries. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask DetectArchiveAsync( + string filePath, + ReaderOptions? readerOptions, + CancellationToken cancellationToken = default + ) => Service.DetectArchiveAsync(filePath, readerOptions, cancellationToken); - public static IEnumerable GetFileParts(FileInfo part1) - { - part1.NotNull(nameof(part1)); - yield return part1; + /// Identify the archive without enumerating its entries. Restore the stream position. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask DetectArchiveAsync( + Stream stream, + CancellationToken cancellationToken = default + ) => Service.DetectArchiveAsync(stream, cancellationToken); - foreach (var factory in Factory.Factories.OfType()) - { - var i = 1; - var part = factory.GetFilePart(i++, part1); + /// Identify the archive without enumerating its entries. Restore the stream position. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask DetectArchiveAsync( + Stream stream, + ReaderOptions? readerOptions, + CancellationToken cancellationToken = default + ) => Service.DetectArchiveAsync(stream, readerOptions, cancellationToken); - if (part != null) - { - yield return part; - while ((part = factory.GetFilePart(i++, part1)) != null) - { - yield return part; - } + /// Inspect archive metadata. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask InspectArchiveAsync( + string filePath, + CancellationToken cancellationToken = default + ) => Service.InspectArchiveAsync(filePath, cancellationToken); - yield break; - } - } - } + /// Inspect archive metadata. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask InspectArchiveAsync( + string filePath, + ReaderOptions? readerOptions, + CancellationToken cancellationToken = default + ) => Service.InspectArchiveAsync(filePath, readerOptions, cancellationToken); + + /// Inspect archive metadata, leaving the stream open at its original position. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask InspectArchiveAsync( + Stream stream, + CancellationToken cancellationToken = default + ) => Service.InspectArchiveAsync(stream, cancellationToken); + + /// Inspect archive metadata, leaving the stream open at its original position. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask InspectArchiveAsync( + Stream stream, + ReaderOptions? readerOptions, + CancellationToken cancellationToken = default + ) => Service.InspectArchiveAsync(stream, readerOptions, cancellationToken); + + /// Inspect multipart archive metadata. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask InspectArchiveAsync( + IReadOnlyList fileInfos, + ReaderOptions? readerOptions = null, + CancellationToken cancellationToken = default + ) => Service.InspectArchiveAsync(fileInfos, readerOptions, cancellationToken); + + /// Inspect multipart archive metadata, leaving the streams open at their original positions. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static ValueTask InspectArchiveAsync( + IReadOnlyList streams, + ReaderOptions? readerOptions = null, + CancellationToken cancellationToken = default + ) => Service.InspectArchiveAsync(streams, readerOptions, cancellationToken); + + public static IEnumerable GetFileParts(string part1) => Service.GetFileParts(part1); + + public static IEnumerable GetFileParts(FileInfo part1) => Service.GetFileParts(part1); } diff --git a/src/SharpCompress/Archives/IArchiveEntryExtensions.cs b/src/SharpCompress/Archives/IArchiveEntryExtensions.cs index b4d858f2..8b54be88 100644 --- a/src/SharpCompress/Archives/IArchiveEntryExtensions.cs +++ b/src/SharpCompress/Archives/IArchiveEntryExtensions.cs @@ -3,12 +3,15 @@ using System.IO; using System.Threading; using System.Threading.Tasks; using SharpCompress.Common; -using SharpCompress.IO; +using SharpCompress.Services; namespace SharpCompress.Archives; public static partial class IArchiveEntryExtensions { + // Give the sync generator a known receiver type before Pure.DI generates the root property. + private static ArchiveExtractor Extractor => LibraryDefaults.Composition.Extractor; + /// The archive entry to extract. extension(IArchiveEntry archiveEntry) { @@ -64,66 +67,17 @@ public static partial class IArchiveEntryExtensions ExtractionOptions? options = null, IProgress? progress = null, CancellationToken cancellationToken = default - ) - { - if (archiveEntry.IsDirectory) - { - throw new ExtractionException("Entry is a file directory and cannot be extracted."); - } - -#if SYNC_ONLY - using var entryStream = archiveEntry.OpenEntryStream(); -#else - var entryStream = await archiveEntry - .OpenEntryStreamAsync(cancellationToken) + ) => + await Extractor + .WriteToAsync( + archiveEntry, + streamToWriteTo, + bufferSize, + options, + progress, + cancellationToken + ) .ConfigureAwait(false); - await using var entryStreamScope = entryStream - .DisposeAsyncScope() - .ConfigureAwait(false); -#endif - var checkedStream = options is null - ? entryStream - : IEntryExtensions.WrapWithChecksumValidation(archiveEntry, entryStream, options); - var sourceStream = WrapWithProgress(checkedStream, archiveEntry, progress); - await sourceStream - .CopyToAsync(streamToWriteTo, bufferSize ?? Constants.BufferSize, cancellationToken) - .ConfigureAwait(false); - } - } - - private static Stream WrapWithProgress( - Stream source, - IArchiveEntry entry, - IProgress? progress - ) - { - if (progress is null) - { - return source; - } - - var entryPath = entry.Key ?? string.Empty; - var totalBytes = GetEntrySizeSafe(entry); - return new ProgressReportingStream( - source, - progress, - entryPath, - totalBytes, - leaveOpen: true - ); - } - - private static long? GetEntrySizeSafe(IArchiveEntry entry) - { - try - { - var size = entry.Size; - return size >= 0 ? size : null; - } - catch (NotImplementedException) - { - return null; - } } extension(IArchiveEntry entry) diff --git a/src/SharpCompress/Readers/ReaderFactory.cs b/src/SharpCompress/Readers/ReaderFactory.cs index 40e95227..09c72ab6 100644 --- a/src/SharpCompress/Readers/ReaderFactory.cs +++ b/src/SharpCompress/Readers/ReaderFactory.cs @@ -1,88 +1,37 @@ -using System; using System.IO; -using System.Linq; -using SharpCompress.Common; -using SharpCompress.Factories; -using SharpCompress.IO; +using System.Threading; +using System.Threading.Tasks; +using SharpCompress.Services; namespace SharpCompress.Readers; public static partial class ReaderFactory { - public static IReader OpenReader(string filePath, ReaderOptions? options = null) - { - filePath.NotNullOrEmpty(nameof(filePath)); - return OpenReader(new FileInfo(filePath), options ?? ReaderOptions.ForFilePath); - } + public static IReader OpenReader(string filePath, ReaderOptions? options = null) => + LibraryDefaults.Composition.Readers.OpenReader(filePath, options); - public static IReader OpenReader(FileInfo fileInfo, ReaderOptions? options = null) - { - options ??= ReaderOptions.ForFilePath; - return OpenReader(fileInfo.OpenRead(), options); - } + public static IReader OpenReader(FileInfo fileInfo, ReaderOptions? options = null) => + LibraryDefaults.Composition.Readers.OpenReader(fileInfo, options); - /// - /// Opens a Reader for Non-seeking usage - /// - /// - /// - /// - public static IReader OpenReader(Stream stream, ReaderOptions? options = null) - { - stream.RequireReadable(); - options ??= ReaderOptions.ForExternalStream; + /// Open a reader for forward-only usage. + public static IReader OpenReader(Stream stream, ReaderOptions? options = null) => + LibraryDefaults.Composition.Readers.OpenReader(stream, options); - if (options.LeaveStreamOpen) - { - // Protect the caller's stream, not the internal wrappers and their pooled buffers. - stream = SharpCompressStream.CreateNonDisposing(stream); - options = options with { LeaveStreamOpen = false }; - } + public static ValueTask OpenAsyncReader( + string filePath, + ReaderOptions? options = null, + CancellationToken cancellationToken = default + ) => LibraryDefaults.Composition.Readers.OpenAsyncReader(filePath, options, cancellationToken); - var sharpCompressStream = SharpCompressStream.Create( - stream, - bufferSize: options.RewindableBufferSize - ); - sharpCompressStream.StartRecording(); + public static ValueTask OpenAsyncReader( + FileInfo fileInfo, + ReaderOptions? options = null, + CancellationToken cancellationToken = default + ) => LibraryDefaults.Composition.Readers.OpenAsyncReader(fileInfo, options, cancellationToken); - var factories = Factories.Factory.Factories.OfType(); - - Factory? testedFactory = null; - - if (!string.IsNullOrWhiteSpace(options.ExtensionHint)) - { - testedFactory = factories.FirstOrDefault(a => - a.GetSupportedExtensions() - .Contains(options.ExtensionHint, StringComparer.CurrentCultureIgnoreCase) - ); - if ( - testedFactory?.TryOpenReader(sharpCompressStream, options, out var reader) == true - && reader != null - ) - { - sharpCompressStream.Rewind(true); - return reader; - } - } - - foreach (var factory in factories) - { - if (testedFactory == factory) - { - continue; // Already tested above - } - sharpCompressStream.Rewind(); - if ( - factory.TryOpenReader(sharpCompressStream, options, out var reader) - && reader != null - ) - { - return reader; - } - } - - throw new InvalidFormatException( - "Cannot determine compressed stream type. Supported Reader Formats: Ace, Arc, Arj, Zip, GZip, BZip2, Tar, Rar, LZip, Lzw, XZ, ZStandard" - ); - } + public static ValueTask OpenAsyncReader( + Stream stream, + ReaderOptions? options = null, + CancellationToken cancellationToken = default + ) => LibraryDefaults.Composition.Readers.OpenAsyncReader(stream, options, cancellationToken); } diff --git a/src/SharpCompress/Services/ArchiveExtractor.cs b/src/SharpCompress/Services/ArchiveExtractor.cs new file mode 100644 index 00000000..c3ca951c --- /dev/null +++ b/src/SharpCompress/Services/ArchiveExtractor.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using SharpCompress.Archives; +using SharpCompress.Common; +using SharpCompress.IO; + +namespace SharpCompress.Services; + +// Destination streams are borrowed, not owned by the reusable extraction service. +internal sealed partial class ArchiveExtractor +{ + [Zomp.SyncMethodGenerator.CreateSyncVersion(PreserveProgress = true)] + public async ValueTask WriteToAsync( + IArchiveEntry archiveEntry, + Stream streamToWriteTo, + int? bufferSize, + ExtractionOptions? options = null, + IProgress? progress = null, + CancellationToken cancellationToken = default + ) + { + if (archiveEntry.IsDirectory) + { + throw new ExtractionException("Entry is a file directory and cannot be extracted."); + } + +#if SYNC_ONLY + using var entryStream = archiveEntry.OpenEntryStream(); +#else + var entryStream = await archiveEntry + .OpenEntryStreamAsync(cancellationToken) + .ConfigureAwait(false); + await using var entryStreamScope = entryStream.DisposeAsyncScope().ConfigureAwait(false); +#endif + var checkedStream = options is null + ? entryStream + : IEntryExtensions.WrapWithChecksumValidation(archiveEntry, entryStream, options); + var sourceStream = WrapWithProgress(checkedStream, archiveEntry, progress); + await sourceStream + .CopyToAsync(streamToWriteTo, bufferSize ?? Constants.BufferSize, cancellationToken) + .ConfigureAwait(false); + } + + private static Stream WrapWithProgress( + Stream source, + IArchiveEntry entry, + IProgress? progress + ) + { + if (progress is null) + { + return source; + } + + var entryPath = entry.Key ?? string.Empty; + var totalBytes = GetEntrySizeSafe(entry); + return new ProgressReportingStream( + source, + progress, + entryPath, + totalBytes, + leaveOpen: true + ); + } + + private static long? GetEntrySizeSafe(IArchiveEntry entry) + { + try + { + var size = entry.Size; + return size >= 0 ? size : null; + } + catch (NotImplementedException) + { + return null; + } + } +} diff --git a/src/SharpCompress/Services/ArchiveFileWriter.cs b/src/SharpCompress/Services/ArchiveFileWriter.cs new file mode 100644 index 00000000..9d256b8f --- /dev/null +++ b/src/SharpCompress/Services/ArchiveFileWriter.cs @@ -0,0 +1,92 @@ +using System; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using SharpCompress.Writers; + +namespace SharpCompress.Services; + +internal sealed class ArchiveFileWriter +{ + public void Write(IWriter writer, string entryPath, FileInfo source) + { + if (!source.Exists) + { + throw new ArgumentException("Source does not exist: " + source.FullName); + } + using var stream = source.OpenRead(); + writer.Write(entryPath, stream, source.LastWriteTime); + } + + public async ValueTask WriteAsync( + IAsyncWriter writer, + string entryPath, + FileInfo source, + CancellationToken cancellationToken = default + ) + { + if (!source.Exists) + { + throw new ArgumentException("Source does not exist: " + source.FullName); + } + var stream = source.OpenRead(); + await using var scope = stream.DisposeAsyncScope().ConfigureAwait(false); + await writer + .WriteAsync(entryPath, stream, source.LastWriteTime, cancellationToken) + .ConfigureAwait(false); + } + + public void WriteAll( + IWriter writer, + string directory, + string searchPattern, + Func? fileSearchFunc, + SearchOption option + ) + { + if (!Directory.Exists(directory)) + { + throw new ArgumentException("Directory does not exist: " + directory); + } + fileSearchFunc ??= n => true; + foreach ( + var file in Directory + .EnumerateFiles(directory, searchPattern, option) + .Where(fileSearchFunc) + ) + { + Write(writer, file.Substring(directory.Length), new FileInfo(file)); + } + } + + public async ValueTask WriteAllAsync( + IAsyncWriter writer, + string directory, + string searchPattern, + Func? fileSearchFunc, + SearchOption option, + CancellationToken cancellationToken = default + ) + { + if (!Directory.Exists(directory)) + { + throw new ArgumentException("Directory does not exist: " + directory); + } + fileSearchFunc ??= n => true; + foreach ( + var file in Directory + .EnumerateFiles(directory, searchPattern, option) + .Where(fileSearchFunc) + ) + { + await WriteAsync( + writer, + file.Substring(directory.Length), + new FileInfo(file), + cancellationToken + ) + .ConfigureAwait(false); + } + } +} diff --git a/src/SharpCompress/Archives/ArchiveFactory.Async.cs b/src/SharpCompress/Services/ArchiveService.Async.cs similarity index 89% rename from src/SharpCompress/Archives/ArchiveFactory.Async.cs rename to src/SharpCompress/Services/ArchiveService.Async.cs index db054211..fd1ac7ef 100644 --- a/src/SharpCompress/Archives/ArchiveFactory.Async.cs +++ b/src/SharpCompress/Services/ArchiveService.Async.cs @@ -3,14 +3,15 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using SharpCompress.Archives; using SharpCompress.Common; using SharpCompress.Readers; -namespace SharpCompress.Archives; +namespace SharpCompress.Services; -public static partial class ArchiveFactory +internal sealed partial class ArchiveService { - public static async ValueTask OpenAsyncArchive( + public async ValueTask OpenAsyncArchive( Stream stream, ReaderOptions? readerOptions = null, CancellationToken cancellationToken = default @@ -28,7 +29,7 @@ public static partial class ArchiveFactory .ConfigureAwait(false); } - public static ValueTask OpenAsyncArchive( + public ValueTask OpenAsyncArchive( string filePath, ReaderOptions? options = null, CancellationToken cancellationToken = default @@ -42,7 +43,7 @@ public static partial class ArchiveFactory ); } - public static async ValueTask OpenAsyncArchive( + public async ValueTask OpenAsyncArchive( FileInfo fileInfo, ReaderOptions? options = null, CancellationToken cancellationToken = default @@ -57,7 +58,7 @@ public static partial class ArchiveFactory .ConfigureAwait(false); } - public static async ValueTask OpenAsyncArchive( + public async ValueTask OpenAsyncArchive( IReadOnlyList fileInfos, ReaderOptions? options = null, CancellationToken cancellationToken = default @@ -91,7 +92,7 @@ public static partial class ArchiveFactory .ConfigureAwait(false); } - public static async ValueTask OpenAsyncArchive( + public async ValueTask OpenAsyncArchive( IReadOnlyList streams, ReaderOptions? options = null, CancellationToken cancellationToken = default diff --git a/src/SharpCompress/Archives/ArchiveFactory.Detection.Async.cs b/src/SharpCompress/Services/ArchiveService.Detection.Async.cs similarity index 91% rename from src/SharpCompress/Archives/ArchiveFactory.Detection.Async.cs rename to src/SharpCompress/Services/ArchiveService.Detection.Async.cs index 04cc7886..8f06d657 100644 --- a/src/SharpCompress/Archives/ArchiveFactory.Detection.Async.cs +++ b/src/SharpCompress/Services/ArchiveService.Detection.Async.cs @@ -2,6 +2,7 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using SharpCompress.Archives; using SharpCompress.Archives.Tar; using SharpCompress.Common; using SharpCompress.Detection; @@ -10,9 +11,9 @@ using SharpCompress.IO; using SharpCompress.Providers; using SharpCompress.Readers; -namespace SharpCompress.Archives; +namespace SharpCompress.Services; -public static partial class ArchiveFactory +internal sealed partial class ArchiveService { /// /// Identifies the archive at the given file path without enumerating its entries. @@ -20,7 +21,7 @@ public static partial class ArchiveFactory /// Path to the archive file. /// Cancellation token. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask DetectArchiveAsync( + public async ValueTask DetectArchiveAsync( string filePath, CancellationToken cancellationToken = default ) => @@ -34,7 +35,7 @@ public static partial class ArchiveFactory /// Options controlling archive detection. /// Cancellation token. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask DetectArchiveAsync( + public async ValueTask DetectArchiveAsync( string filePath, ReaderOptions? readerOptions, CancellationToken cancellationToken = default @@ -56,7 +57,7 @@ public static partial class ArchiveFactory /// A readable and seekable stream positioned at the start of the archive. /// Cancellation token. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask DetectArchiveAsync( + public async ValueTask DetectArchiveAsync( Stream stream, CancellationToken cancellationToken = default ) => @@ -70,7 +71,7 @@ public static partial class ArchiveFactory /// Options controlling archive detection. /// Cancellation token. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask DetectArchiveAsync( + public async ValueTask DetectArchiveAsync( Stream stream, ReaderOptions? readerOptions, CancellationToken cancellationToken = default @@ -87,7 +88,7 @@ public static partial class ArchiveFactory .ConfigureAwait(false); } - internal static ValueTask FindFactoryAsync( + internal ValueTask FindFactoryAsync( string filePath, CancellationToken cancellationToken = default ) @@ -97,7 +98,7 @@ public static partial class ArchiveFactory return FindFactoryAsync(new FileInfo(filePath), cancellationToken); } - internal static async ValueTask FindFactoryAsync( + internal async ValueTask FindFactoryAsync( FileInfo fileInfo, CancellationToken cancellationToken = default ) @@ -109,7 +110,7 @@ public static partial class ArchiveFactory } [Zomp.SyncMethodGenerator.CreateSyncVersion] - private static async ValueTask FindFactoryAsync( + private async ValueTask FindFactoryAsync( FileInfo fileInfo, ReaderOptions readerOptions, CancellationToken cancellationToken @@ -122,7 +123,7 @@ public static partial class ArchiveFactory .ConfigureAwait(false); } - internal static async ValueTask FindFactoryAsync( + internal async ValueTask FindFactoryAsync( Stream stream, CancellationToken cancellationToken = default ) @@ -140,7 +141,7 @@ public static partial class ArchiveFactory } [Zomp.SyncMethodGenerator.CreateSyncVersion] - private static async ValueTask FindFactoryAsync( + private async ValueTask FindFactoryAsync( Stream stream, ReaderOptions readerOptions, CancellationToken cancellationToken @@ -157,7 +158,7 @@ public static partial class ArchiveFactory return typedFactory; } - var extensions = string.Join(", ", Factory.Factories.OfType().Select(item => item.Name)); + var extensions = string.Join(", ", catalog.Factories.OfType().Select(item => item.Name)); throw new ArchiveOperationException( $"Cannot determine compressed stream type. Supported Archive Formats: {extensions}" @@ -170,7 +171,7 @@ public static partial class ArchiveFactory /// Stream position is restored to its value at entry on both success and failure. /// [Zomp.SyncMethodGenerator.CreateSyncVersion] - private static async ValueTask TryFindFactoryAsync( + private async ValueTask TryFindFactoryAsync( Stream stream, ReaderOptions readerOptions, CancellationToken cancellationToken @@ -180,7 +181,7 @@ public static partial class ArchiveFactory try { - foreach (var factory in Factory.Factories) + foreach (var factory in catalog.Factories) { stream.Seek(startPosition, SeekOrigin.Begin); var isArchive = await factory @@ -268,7 +269,7 @@ public static partial class ArchiveFactory } [Zomp.SyncMethodGenerator.CreateSyncVersion] - private static async ValueTask TryDetectArchiveAsync( + private async ValueTask TryDetectArchiveAsync( Stream stream, ReaderOptions readerOptions, CancellationToken cancellationToken @@ -278,7 +279,7 @@ public static partial class ArchiveFactory try { - foreach (var factory in Factory.Factories) + foreach (var factory in catalog.Factories) { stream.Seek(startPosition, SeekOrigin.Begin); if ( @@ -326,14 +327,14 @@ public static partial class ArchiveFactory } [Zomp.SyncMethodGenerator.CreateSyncVersion] - private static async ValueTask TryDetectCompressedTarAsync( + private async ValueTask TryDetectCompressedTarAsync( Stream stream, ReaderOptions readerOptions, long startPosition, CancellationToken cancellationToken ) { - foreach (var wrapper in TarWrapper.Wrappers) + foreach (var wrapper in catalog.Wrappers) { #if !SYNC_ONLY cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/SharpCompress/Archives/ArchiveFactory.Detection.cs b/src/SharpCompress/Services/ArchiveService.Detection.cs similarity index 92% rename from src/SharpCompress/Archives/ArchiveFactory.Detection.cs rename to src/SharpCompress/Services/ArchiveService.Detection.cs index 85721dbf..649f5022 100644 --- a/src/SharpCompress/Archives/ArchiveFactory.Detection.cs +++ b/src/SharpCompress/Services/ArchiveService.Detection.cs @@ -1,12 +1,13 @@ using System.IO; +using SharpCompress.Archives; using SharpCompress.Common; using SharpCompress.Detection; using SharpCompress.Factories; using SharpCompress.Readers; -namespace SharpCompress.Archives; +namespace SharpCompress.Services; -public static partial class ArchiveFactory +internal sealed partial class ArchiveService { private static void DisposeProbeStream(Stream stream) { diff --git a/src/SharpCompress/Archives/ArchiveFactory.Information.Async.cs b/src/SharpCompress/Services/ArchiveService.Information.Async.cs similarity index 96% rename from src/SharpCompress/Archives/ArchiveFactory.Information.Async.cs rename to src/SharpCompress/Services/ArchiveService.Information.Async.cs index 8ac74f5d..3d160af7 100644 --- a/src/SharpCompress/Archives/ArchiveFactory.Information.Async.cs +++ b/src/SharpCompress/Services/ArchiveService.Information.Async.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using SharpCompress.Archives; using SharpCompress.Archives.Rar; using SharpCompress.Archives.SevenZip; using SharpCompress.Archives.Zip; @@ -15,9 +16,9 @@ using SharpCompress.Detection; using SharpCompress.IO; using SharpCompress.Readers; -namespace SharpCompress.Archives; +namespace SharpCompress.Services; -public static partial class ArchiveFactory +internal sealed partial class ArchiveService { /// /// Collects metadata for the archive at the given file path. @@ -26,7 +27,7 @@ public static partial class ArchiveFactory /// Cancellation token. /// Archive metadata, or when the file is not a supported archive. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask InspectArchiveAsync( + public async ValueTask InspectArchiveAsync( string filePath, CancellationToken cancellationToken = default ) => @@ -41,7 +42,7 @@ public static partial class ArchiveFactory /// Cancellation token. /// Archive metadata, or when the file is not a supported archive. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask InspectArchiveAsync( + public async ValueTask InspectArchiveAsync( string filePath, ReaderOptions? readerOptions, CancellationToken cancellationToken = default @@ -76,7 +77,7 @@ public static partial class ArchiveFactory /// Cancellation token. /// Archive metadata, or when the stream is not a supported archive. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask InspectArchiveAsync( + public async ValueTask InspectArchiveAsync( Stream stream, CancellationToken cancellationToken = default ) => @@ -92,7 +93,7 @@ public static partial class ArchiveFactory /// Archive metadata, or when the stream is not a supported archive. /// The supplied stream remains open and is restored to its original position. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask InspectArchiveAsync( + public async ValueTask InspectArchiveAsync( Stream stream, ReaderOptions? readerOptions, CancellationToken cancellationToken = default @@ -148,7 +149,7 @@ public static partial class ArchiveFactory #if SYNC_ONLY var aceHeader = ReadAceHeader(archiveStream, detection, inspectionOptions); - using var reader = ReaderFactory.OpenReader(archiveStream, inspectionOptions); + using var reader = readers.OpenReader(archiveStream, inspectionOptions); return InspectOpenedReader(reader, detection, physicalSize, 1, aceHeader); #else var aceHeader = await ReadAceHeaderAsync( @@ -158,7 +159,7 @@ public static partial class ArchiveFactory cancellationToken ) .ConfigureAwait(false); - await using var reader = await ReaderFactory + await using var reader = await readers .OpenAsyncReader(archiveStream, inspectionOptions, cancellationToken) .ConfigureAwait(false); return await InspectOpenedReaderAsync( @@ -222,7 +223,7 @@ public static partial class ArchiveFactory /// Cancellation token. /// Archive metadata, or when the files are not a supported archive. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask InspectArchiveAsync( + public async ValueTask InspectArchiveAsync( IReadOnlyList fileInfos, ReaderOptions? readerOptions = null, CancellationToken cancellationToken = default @@ -295,7 +296,7 @@ public static partial class ArchiveFactory /// Cancellation token. /// Archive metadata, or when the streams are not a supported archive. [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async ValueTask InspectArchiveAsync( + public async ValueTask InspectArchiveAsync( IReadOnlyList streams, ReaderOptions? readerOptions = null, CancellationToken cancellationToken = default @@ -597,7 +598,7 @@ public static partial class ArchiveFactory } [Zomp.SyncMethodGenerator.CreateSyncVersion] - private static async ValueTask RedetectArchiveAsync( + private async ValueTask RedetectArchiveAsync( Stream stream, long startPosition, ReaderOptions options, diff --git a/src/SharpCompress/Archives/ArchiveFactory.Information.cs b/src/SharpCompress/Services/ArchiveService.Information.cs similarity index 98% rename from src/SharpCompress/Archives/ArchiveFactory.Information.cs rename to src/SharpCompress/Services/ArchiveService.Information.cs index 4b12fe8d..b60d4f7f 100644 --- a/src/SharpCompress/Archives/ArchiveFactory.Information.cs +++ b/src/SharpCompress/Services/ArchiveService.Information.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using SharpCompress.Archives; using SharpCompress.Archives.Rar; using SharpCompress.Archives.SevenZip; using SharpCompress.Archives.Zip; @@ -13,9 +14,9 @@ using SharpCompress.Detection; using SharpCompress.Readers; using AceMainHeader = SharpCompress.Common.Ace.Headers.AceMainHeader; -namespace SharpCompress.Archives; +namespace SharpCompress.Services; -public static partial class ArchiveFactory +internal sealed partial class ArchiveService { private static ArchiveInformation InspectOpenedArchive( IArchive archive, @@ -231,7 +232,7 @@ public static partial class ArchiveFactory } } - private static FileInfo[] GetArchiveFileParts(FileInfo firstPart, ReaderOptions options) + private FileInfo[] GetArchiveFileParts(FileInfo firstPart, ReaderOptions options) { using Stream stream = firstPart.OpenRead(); var factory = TryFindFactory(stream, options); diff --git a/src/SharpCompress/Services/ArchiveService.cs b/src/SharpCompress/Services/ArchiveService.cs new file mode 100644 index 00000000..c9e087c3 --- /dev/null +++ b/src/SharpCompress/Services/ArchiveService.cs @@ -0,0 +1,227 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using SharpCompress.Archives; +using SharpCompress.Common; +using SharpCompress.Common.Options; +using SharpCompress.Factories; +using SharpCompress.Readers; + +namespace SharpCompress.Services; + +internal sealed partial class ArchiveService(FactoryCatalog catalog, ReaderService readers) +{ + public IArchive OpenArchive(Stream stream, ReaderOptions? readerOptions = null) + { + readerOptions ??= ReaderOptions.ForExternalStream; + return FindFactory(stream, readerOptions) + .OpenArchive(stream, readerOptions); + } + + public IWritableArchive CreateArchive() + where TOptions : IWriterOptions + { + var factory = catalog + .Factories.OfType>() + .FirstOrDefault(); + + if (factory != null) + { + return factory.CreateArchive(); + } + + throw new NotSupportedException("Cannot create Archives of type: " + typeof(TOptions)); + } + + public IArchive OpenArchive(string filePath, ReaderOptions? options = null) + { + filePath.NotNullOrEmpty(nameof(filePath)); + return OpenArchive(new FileInfo(filePath), options ?? ReaderOptions.ForFilePath); + } + + public IArchive OpenArchive(FileInfo fileInfo, ReaderOptions? options = null) + { + options ??= ReaderOptions.ForFilePath; + + return FindFactory(fileInfo, options).OpenArchive(fileInfo, options); + } + + public IArchive OpenArchive(IReadOnlyList fileInfos, ReaderOptions? options = null) + { + fileInfos.NotNull(nameof(fileInfos)); + var filesArray = fileInfos; + if (filesArray.Count == 0) + { + throw new ArchiveOperationException("No files to open"); + } + + var fileInfo = filesArray[0]; + if (filesArray.Count == 1) + { + return OpenArchive(fileInfo, options); + } + + fileInfo.NotNull(nameof(fileInfo)); + options ??= ReaderOptions.ForFilePath; + + return FindFactory(fileInfo, options) + .OpenArchive(filesArray, options); + } + + public IArchive OpenArchive(IReadOnlyList streams, ReaderOptions? options = null) + { + var streamsArray = streams.RequireReadable().RequireSeekable().ToList(); + if (streamsArray.Count == 0) + { + throw new ArchiveOperationException("No streams"); + } + + var firstStream = streamsArray[0]; + if (streamsArray.Count == 1) + { + return OpenArchive(firstStream, options); + } + + firstStream.NotNull(nameof(firstStream)); + options ??= ReaderOptions.ForExternalStream; + + return FindFactory(firstStream, options) + .OpenArchive(streamsArray, options); + } + + public void WriteToDirectory( + string sourceArchive, + string destinationDirectory, + ExtractionOptions? options = null + ) + { + using var archive = OpenArchive(sourceArchive); + archive.WriteToDirectory(destinationDirectory, options); + } + + public T FindFactory(string filePath) + where T : IFactory + { + filePath.NotNullOrEmpty(nameof(filePath)); + using Stream stream = File.OpenRead(filePath); + return FindFactory(stream); + } + + public T FindFactory(FileInfo finfo) + where T : IFactory + { + finfo.NotNull(nameof(finfo)); + using Stream stream = finfo.OpenRead(); + return FindFactory(stream); + } + + public T FindFactory(Stream stream) + where T : IFactory => FindFactory(stream, ReaderOptions.ForExternalStream); + + public bool IsArchive(string filePath, out ArchiveType? type) + { + return IsArchive(filePath, ReaderOptions.ForFilePath, out type); + } + + public bool IsArchive(string filePath, ReaderOptions? readerOptions, out ArchiveType? type) + { + filePath.NotNullOrEmpty(nameof(filePath)); + using Stream s = File.OpenRead(filePath); + return IsArchive(s, readerOptions ?? ReaderOptions.ForFilePath, out type); + } + + public bool IsArchive(Stream stream, out ArchiveType? type) + { + return IsArchive(stream, ReaderOptions.ForExternalStream, out type); + } + + public bool IsArchive(Stream stream, ReaderOptions? readerOptions, out ArchiveType? type) + { + stream.RequireReadable(); + stream.RequireSeekable(); + + var factory = TryFindFactory(stream, readerOptions ?? ReaderOptions.ForExternalStream); + type = factory?.KnownArchiveType; + return factory is not null; + } + + public async ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( + string filePath, + CancellationToken cancellationToken = default + ) => + await IsArchiveAsync(filePath, ReaderOptions.ForFilePath, cancellationToken) + .ConfigureAwait(false); + + public async ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( + string filePath, + ReaderOptions? readerOptions, + CancellationToken cancellationToken = default + ) + { + filePath.NotNullOrEmpty(nameof(filePath)); + using Stream stream = File.OpenRead(filePath); + return await IsArchiveAsync( + stream, + readerOptions ?? ReaderOptions.ForFilePath, + cancellationToken + ) + .ConfigureAwait(false); + } + + public async ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( + Stream stream, + CancellationToken cancellationToken = default + ) => + await IsArchiveAsync(stream, ReaderOptions.ForExternalStream, cancellationToken) + .ConfigureAwait(false); + + public async ValueTask<(bool IsArchive, ArchiveType? Type)> IsArchiveAsync( + Stream stream, + ReaderOptions? readerOptions, + CancellationToken cancellationToken = default + ) + { + stream.RequireReadable(); + stream.RequireSeekable(); + + var factory = await TryFindFactoryAsync( + stream, + readerOptions ?? ReaderOptions.ForExternalStream, + cancellationToken + ) + .ConfigureAwait(false); + return (factory is not null, factory?.KnownArchiveType); + } + + public IEnumerable GetFileParts(string part1) + { + part1.NotNullOrEmpty(nameof(part1)); + return GetFileParts(new FileInfo(part1)).Select(a => a.FullName); + } + + public IEnumerable GetFileParts(FileInfo part1) + { + part1.NotNull(nameof(part1)); + yield return part1; + + foreach (var factory in catalog.Factories.OfType()) + { + var i = 1; + var part = factory.GetFilePart(i++, part1); + + if (part != null) + { + yield return part; + while ((part = factory.GetFilePart(i++, part1)) != null) + { + yield return part; + } + + yield break; + } + } + } +} diff --git a/src/SharpCompress/Services/FactoryCatalog.cs b/src/SharpCompress/Services/FactoryCatalog.cs new file mode 100644 index 00000000..bc8aee83 --- /dev/null +++ b/src/SharpCompress/Services/FactoryCatalog.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using SharpCompress.Factories; + +namespace SharpCompress.Services; + +// Read through on each operation: legacy registrations made after composition must remain visible. +internal sealed class FactoryCatalog( + Func> factories, + Func> wrappers +) +{ + public IEnumerable Factories => factories(); + public IEnumerable Wrappers => wrappers(); +} diff --git a/src/SharpCompress/Readers/ReaderFactory.Async.cs b/src/SharpCompress/Services/ReaderService.Async.cs similarity index 91% rename from src/SharpCompress/Readers/ReaderFactory.Async.cs rename to src/SharpCompress/Services/ReaderService.Async.cs index dd1850bf..8d80a8d8 100644 --- a/src/SharpCompress/Readers/ReaderFactory.Async.cs +++ b/src/SharpCompress/Services/ReaderService.Async.cs @@ -6,10 +6,11 @@ using System.Threading.Tasks; using SharpCompress.Common; using SharpCompress.Factories; using SharpCompress.IO; +using SharpCompress.Readers; -namespace SharpCompress.Readers; +namespace SharpCompress.Services; -public static partial class ReaderFactory +internal sealed partial class ReaderService { /// /// Opens a Reader from a filepath asynchronously @@ -18,7 +19,7 @@ public static partial class ReaderFactory /// /// /// - public static ValueTask OpenAsyncReader( + public ValueTask OpenAsyncReader( string filePath, ReaderOptions? options = null, CancellationToken cancellationToken = default @@ -39,7 +40,7 @@ public static partial class ReaderFactory /// /// /// - public static async ValueTask OpenAsyncReader( + public async ValueTask OpenAsyncReader( FileInfo fileInfo, ReaderOptions? options = null, CancellationToken cancellationToken = default @@ -50,7 +51,7 @@ public static partial class ReaderFactory return await OpenAsyncReader(stream, options, cancellationToken).ConfigureAwait(false); } - public static async ValueTask OpenAsyncReader( + public async ValueTask OpenAsyncReader( Stream stream, ReaderOptions? options = null, CancellationToken cancellationToken = default @@ -72,7 +73,7 @@ public static partial class ReaderFactory ); sharpCompressStream.StartRecording(); - var factories = Factory.Factories.OfType(); + var factories = catalog.Factories.OfType(); Factory? testedFactory = null; if (!string.IsNullOrWhiteSpace(options.ExtensionHint)) diff --git a/src/SharpCompress/Services/ReaderService.cs b/src/SharpCompress/Services/ReaderService.cs new file mode 100644 index 00000000..7d07208b --- /dev/null +++ b/src/SharpCompress/Services/ReaderService.cs @@ -0,0 +1,89 @@ +using System; +using System.IO; +using System.Linq; +using SharpCompress.Common; +using SharpCompress.Factories; +using SharpCompress.IO; +using SharpCompress.Readers; + +namespace SharpCompress.Services; + +internal sealed partial class ReaderService(FactoryCatalog catalog) +{ + public IReader OpenReader(string filePath, ReaderOptions? options = null) + { + filePath.NotNullOrEmpty(nameof(filePath)); + return OpenReader(new FileInfo(filePath), options ?? ReaderOptions.ForFilePath); + } + + public IReader OpenReader(FileInfo fileInfo, ReaderOptions? options = null) + { + options ??= ReaderOptions.ForFilePath; + return OpenReader(fileInfo.OpenRead(), options); + } + + /// + /// Opens a Reader for Non-seeking usage + /// + /// + /// + /// + public IReader OpenReader(Stream stream, ReaderOptions? options = null) + { + stream.RequireReadable(); + options ??= ReaderOptions.ForExternalStream; + + if (options.LeaveStreamOpen) + { + // Protect the caller's stream, not the internal wrappers and their pooled buffers. + stream = SharpCompressStream.CreateNonDisposing(stream); + options = options with { LeaveStreamOpen = false }; + } + + var sharpCompressStream = SharpCompressStream.Create( + stream, + bufferSize: options.RewindableBufferSize + ); + sharpCompressStream.StartRecording(); + + var factories = catalog.Factories.OfType(); + + Factory? testedFactory = null; + + if (!string.IsNullOrWhiteSpace(options.ExtensionHint)) + { + testedFactory = factories.FirstOrDefault(a => + a.GetSupportedExtensions() + .Contains(options.ExtensionHint, StringComparer.CurrentCultureIgnoreCase) + ); + if ( + testedFactory?.TryOpenReader(sharpCompressStream, options, out var reader) == true + && reader != null + ) + { + sharpCompressStream.Rewind(true); + return reader; + } + } + + foreach (var factory in factories) + { + if (testedFactory == factory) + { + continue; // Already tested above + } + sharpCompressStream.Rewind(); + if ( + factory.TryOpenReader(sharpCompressStream, options, out var reader) + && reader != null + ) + { + return reader; + } + } + + throw new InvalidFormatException( + "Cannot determine compressed stream type. Supported Reader Formats: Ace, Arc, Arj, Zip, GZip, BZip2, Tar, Rar, LZip, Lzw, XZ, ZStandard" + ); + } +} diff --git a/src/SharpCompress/Services/ServiceComposition.cs b/src/SharpCompress/Services/ServiceComposition.cs new file mode 100644 index 00000000..5b55e6c1 --- /dev/null +++ b/src/SharpCompress/Services/ServiceComposition.cs @@ -0,0 +1,40 @@ +using Pure.DI; +using SharpCompress.Factories; + +namespace SharpCompress.Services; + +// Only stateless workflow services are composed. Returned archives and streams stay caller-owned. +internal partial class ServiceComposition +{ + private static void Setup() => + DI.Setup() + .Hint(Hint.Resolve, "Off") + .Arg("catalog") + .Bind() + .As(Lifetime.Singleton) + .To() + .Bind() + .As(Lifetime.Singleton) + .To() + .Bind() + .As(Lifetime.Singleton) + .To() + .Bind() + .As(Lifetime.Singleton) + .To() + .Bind() + .As(Lifetime.Singleton) + .To() + .Root("Archives") + .Root("Readers") + .Root("Writers") + .Root("Extractor") + .Root("FileWriter"); +} + +internal static class LibraryDefaults +{ + // Do not construct built-in factories here: Factory owns their initialization and registration. + public static ServiceComposition Composition { get; } = + new(new FactoryCatalog(() => Factory.Factories, () => TarWrapper.Wrappers)); +} diff --git a/src/SharpCompress/Services/WriterService.cs b/src/SharpCompress/Services/WriterService.cs new file mode 100644 index 00000000..41c1f69f --- /dev/null +++ b/src/SharpCompress/Services/WriterService.cs @@ -0,0 +1,120 @@ +using System; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using SharpCompress.Common; +using SharpCompress.Common.Options; +using SharpCompress.Factories; +using SharpCompress.Writers; + +namespace SharpCompress.Services; + +internal sealed class WriterService(FactoryCatalog catalog) +{ + public IWriter OpenWriter( + string filePath, + ArchiveType archiveType, + IWriterOptions writerOptions + ) + { + filePath.NotNullOrEmpty(nameof(filePath)); + return OpenWriter(new FileInfo(filePath), archiveType, writerOptions); + } + + public IWriter OpenWriter( + FileInfo fileInfo, + ArchiveType archiveType, + IWriterOptions writerOptions + ) + { + fileInfo.NotNull(nameof(fileInfo)); + return OpenWriter( + fileInfo.OpenWrite(), + archiveType, + writerOptions.WithLeaveStreamOpen(false) + ); + } + + public async ValueTask OpenAsyncWriter( + string filePath, + ArchiveType archiveType, + IWriterOptions writerOptions, + CancellationToken cancellationToken = default + ) + { + filePath.NotNullOrEmpty(nameof(filePath)); + return await OpenAsyncWriter( + new FileInfo(filePath), + archiveType, + writerOptions, + cancellationToken + ) + .ConfigureAwait(false); + } + + public async ValueTask OpenAsyncWriter( + FileInfo fileInfo, + ArchiveType archiveType, + IWriterOptions writerOptions, + CancellationToken cancellationToken = default + ) + { + fileInfo.NotNull(nameof(fileInfo)); + var stream = fileInfo.OpenAsyncWriteStream(cancellationToken); + return await OpenAsyncWriter( + stream, + archiveType, + writerOptions.WithLeaveStreamOpen(false), + cancellationToken + ) + .ConfigureAwait(false); + } + + public IWriter OpenWriter(Stream stream, ArchiveType archiveType, IWriterOptions writerOptions) + { + stream.RequireWritable(); + + var factory = catalog + .Factories.OfType() + .FirstOrDefault(item => item.KnownArchiveType == archiveType); + + if (factory != null) + { + return factory.OpenWriter(stream, writerOptions); + } + + throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); + } + + /// + /// Opens a Writer asynchronously. + /// + /// The stream to write to. + /// The archive type. + /// Writer options. + /// Cancellation token. + /// A containing the async writer. + public async ValueTask OpenAsyncWriter( + Stream stream, + ArchiveType archiveType, + IWriterOptions writerOptions, + CancellationToken cancellationToken = default + ) + { + stream.RequireWritable(); + + var factory = catalog + .Factories.OfType() + .FirstOrDefault(item => item.KnownArchiveType == archiveType); + + if (factory != null) + { + return await factory + .OpenAsyncWriter(stream, writerOptions, cancellationToken) + .ConfigureAwait(false); + } + + throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); + } +} diff --git a/src/SharpCompress/SharpCompress.csproj b/src/SharpCompress/SharpCompress.csproj index d5ba7f80..6e5f4b88 100644 --- a/src/SharpCompress/SharpCompress.csproj +++ b/src/SharpCompress/SharpCompress.csproj @@ -43,6 +43,7 @@ + diff --git a/src/SharpCompress/Writers/IWriterExtensions.cs b/src/SharpCompress/Writers/IWriterExtensions.cs index b1a082f9..6d81da56 100644 --- a/src/SharpCompress/Writers/IWriterExtensions.cs +++ b/src/SharpCompress/Writers/IWriterExtensions.cs @@ -1,8 +1,8 @@ using System; using System.IO; -using System.Linq; using System.Threading; using System.Threading.Tasks; +using SharpCompress.Services; namespace SharpCompress.Writers; @@ -12,16 +12,8 @@ public static class IWriterExtensions { public void Write(string entryPath, Stream source) => writer.Write(entryPath, source, null); - public void Write(string entryPath, FileInfo source) - { - if (!source.Exists) - { - throw new ArgumentException("Source does not exist: " + source.FullName); - } - - using var stream = source.OpenRead(); - writer.Write(entryPath, stream, source.LastWriteTime); - } + public void Write(string entryPath, FileInfo source) => + LibraryDefaults.Composition.FileWriter.Write(writer, entryPath, source); public void Write(string entryPath, string source) => writer.Write(entryPath, new FileInfo(source)); @@ -37,23 +29,14 @@ public static class IWriterExtensions string searchPattern = "*", Func? fileSearchFunc = null, SearchOption option = SearchOption.TopDirectoryOnly - ) - { - if (!Directory.Exists(directory)) - { - throw new ArgumentException("Directory does not exist: " + directory); - } - - fileSearchFunc ??= n => true; - foreach ( - var file in Directory - .EnumerateFiles(directory, searchPattern, option) - .Where(fileSearchFunc) - ) - { - writer.Write(file.Substring(directory.Length), file); - } - } + ) => + LibraryDefaults.Composition.FileWriter.WriteAll( + writer, + directory, + searchPattern, + fileSearchFunc, + option + ); public void WriteDirectory(string directoryName) => writer.WriteDirectory(directoryName, null); @@ -71,18 +54,10 @@ public static class IWriterExtensions string entryPath, FileInfo source, CancellationToken cancellationToken = default - ) - { - if (!source.Exists) - { - throw new ArgumentException("Source does not exist: " + source.FullName); - } - var stream = source.OpenRead(); - await using var scope = stream.DisposeAsyncScope().ConfigureAwait(false); - await writer - .WriteAsync(entryPath, stream, source.LastWriteTime, cancellationToken) + ) => + await LibraryDefaults + .Composition.FileWriter.WriteAsync(writer, entryPath, source, cancellationToken) .ConfigureAwait(false); - } public ValueTask WriteAsync( string entryPath, @@ -103,25 +78,17 @@ public static class IWriterExtensions Func? fileSearchFunc = null, SearchOption option = SearchOption.TopDirectoryOnly, CancellationToken cancellationToken = default - ) - { - if (!Directory.Exists(directory)) - { - throw new ArgumentException("Directory does not exist: " + directory); - } - - fileSearchFunc ??= n => true; - foreach ( - var file in Directory - .EnumerateFiles(directory, searchPattern, option) - .Where(fileSearchFunc) - ) - { - await writer - .WriteAsync(file.Substring(directory.Length), file, cancellationToken) - .ConfigureAwait(false); - } - } + ) => + await LibraryDefaults + .Composition.FileWriter.WriteAllAsync( + writer, + directory, + searchPattern, + fileSearchFunc, + option, + cancellationToken + ) + .ConfigureAwait(false); public ValueTask WriteDirectoryAsync( string directoryName, diff --git a/src/SharpCompress/Writers/WriterFactory.cs b/src/SharpCompress/Writers/WriterFactory.cs index 847766f9..bf676b6c 100644 --- a/src/SharpCompress/Writers/WriterFactory.cs +++ b/src/SharpCompress/Writers/WriterFactory.cs @@ -1,10 +1,9 @@ -using System; using System.IO; -using System.Linq; using System.Threading; using System.Threading.Tasks; using SharpCompress.Common; using SharpCompress.Common.Options; +using SharpCompress.Services; namespace SharpCompress.Writers; @@ -14,109 +13,56 @@ public static class WriterFactory string filePath, ArchiveType archiveType, IWriterOptions writerOptions - ) - { - filePath.NotNullOrEmpty(nameof(filePath)); - return OpenWriter(new FileInfo(filePath), archiveType, writerOptions); - } + ) => LibraryDefaults.Composition.Writers.OpenWriter(filePath, archiveType, writerOptions); public static IWriter OpenWriter( FileInfo fileInfo, ArchiveType archiveType, IWriterOptions writerOptions - ) - { - fileInfo.NotNull(nameof(fileInfo)); - return OpenWriter( - fileInfo.OpenWrite(), - archiveType, - writerOptions.WithLeaveStreamOpen(false) - ); - } + ) => LibraryDefaults.Composition.Writers.OpenWriter(fileInfo, archiveType, writerOptions); - public static async ValueTask OpenAsyncWriter( + public static IWriter OpenWriter( + Stream stream, + ArchiveType archiveType, + IWriterOptions writerOptions + ) => LibraryDefaults.Composition.Writers.OpenWriter(stream, archiveType, writerOptions); + + public static ValueTask OpenAsyncWriter( string filePath, ArchiveType archiveType, IWriterOptions writerOptions, CancellationToken cancellationToken = default - ) - { - filePath.NotNullOrEmpty(nameof(filePath)); - return await OpenAsyncWriter( - new FileInfo(filePath), - archiveType, - writerOptions, - cancellationToken - ) - .ConfigureAwait(false); - } + ) => + LibraryDefaults.Composition.Writers.OpenAsyncWriter( + filePath, + archiveType, + writerOptions, + cancellationToken + ); - public static async ValueTask OpenAsyncWriter( + public static ValueTask OpenAsyncWriter( FileInfo fileInfo, ArchiveType archiveType, IWriterOptions writerOptions, CancellationToken cancellationToken = default - ) - { - fileInfo.NotNull(nameof(fileInfo)); - var stream = fileInfo.OpenAsyncWriteStream(cancellationToken); - return await OpenAsyncWriter( - stream, - archiveType, - writerOptions.WithLeaveStreamOpen(false), - cancellationToken - ) - .ConfigureAwait(false); - } + ) => + LibraryDefaults.Composition.Writers.OpenAsyncWriter( + fileInfo, + archiveType, + writerOptions, + cancellationToken + ); - public static IWriter OpenWriter( - Stream stream, - ArchiveType archiveType, - IWriterOptions writerOptions - ) - { - stream.RequireWritable(); - - var factory = Factories - .Factory.Factories.OfType() - .FirstOrDefault(item => item.KnownArchiveType == archiveType); - - if (factory != null) - { - return factory.OpenWriter(stream, writerOptions); - } - - throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); - } - - /// - /// Opens a Writer asynchronously. - /// - /// The stream to write to. - /// The archive type. - /// Writer options. - /// Cancellation token. - /// A containing the async writer. - public static async ValueTask OpenAsyncWriter( + public static ValueTask OpenAsyncWriter( Stream stream, ArchiveType archiveType, IWriterOptions writerOptions, CancellationToken cancellationToken = default - ) - { - stream.RequireWritable(); - - var factory = Factories - .Factory.Factories.OfType() - .FirstOrDefault(item => item.KnownArchiveType == archiveType); - - if (factory != null) - { - return await factory - .OpenAsyncWriter(stream, writerOptions, cancellationToken) - .ConfigureAwait(false); - } - - throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType); - } + ) => + LibraryDefaults.Composition.Writers.OpenAsyncWriter( + stream, + archiveType, + writerOptions, + cancellationToken + ); } diff --git a/src/SharpCompress/packages.lock.json b/src/SharpCompress/packages.lock.json index 6afa698b..308461ce 100644 --- a/src/SharpCompress/packages.lock.json +++ b/src/SharpCompress/packages.lock.json @@ -43,6 +43,12 @@ "resolved": "1.16.0", "contentHash": "3kdIIceBPumwjw279FuiVMfVENT2cGASXJgcigdySsbX2dJB8ofUgG6i47yqF/k1qu6fvNR3csrSekZPviR6kQ==" }, + "Pure.DI": { + "type": "Direct", + "requested": "[2.5.4, )", + "resolved": "2.5.4", + "contentHash": "Q4F67gdTdbrc+9c+EjZqPiyxywXC5LVdJpKdENtHfK1XpGJ3UWPZB7rhhuqqDVbcbr1EX1r5aGw1Wm/vlXWy2A==" + }, "System.Text.Encoding.CodePages": { "type": "Direct", "requested": "[10.0.12, )", @@ -177,6 +183,12 @@ "resolved": "1.16.0", "contentHash": "3kdIIceBPumwjw279FuiVMfVENT2cGASXJgcigdySsbX2dJB8ofUgG6i47yqF/k1qu6fvNR3csrSekZPviR6kQ==" }, + "Pure.DI": { + "type": "Direct", + "requested": "[2.5.4, )", + "resolved": "2.5.4", + "contentHash": "Q4F67gdTdbrc+9c+EjZqPiyxywXC5LVdJpKdENtHfK1XpGJ3UWPZB7rhhuqqDVbcbr1EX1r5aGw1Wm/vlXWy2A==" + }, "System.Text.Encoding.CodePages": { "type": "Direct", "requested": "[10.0.12, )", @@ -298,6 +310,12 @@ "resolved": "1.16.0", "contentHash": "3kdIIceBPumwjw279FuiVMfVENT2cGASXJgcigdySsbX2dJB8ofUgG6i47yqF/k1qu6fvNR3csrSekZPviR6kQ==" }, + "Pure.DI": { + "type": "Direct", + "requested": "[2.5.4, )", + "resolved": "2.5.4", + "contentHash": "Q4F67gdTdbrc+9c+EjZqPiyxywXC5LVdJpKdENtHfK1XpGJ3UWPZB7rhhuqqDVbcbr1EX1r5aGw1Wm/vlXWy2A==" + }, "System.Text.Encoding.CodePages": { "type": "Direct", "requested": "[10.0.12, )", @@ -381,6 +399,12 @@ "resolved": "1.16.0", "contentHash": "3kdIIceBPumwjw279FuiVMfVENT2cGASXJgcigdySsbX2dJB8ofUgG6i47yqF/k1qu6fvNR3csrSekZPviR6kQ==" }, + "Pure.DI": { + "type": "Direct", + "requested": "[2.5.4, )", + "resolved": "2.5.4", + "contentHash": "Q4F67gdTdbrc+9c+EjZqPiyxywXC5LVdJpKdENtHfK1XpGJ3UWPZB7rhhuqqDVbcbr1EX1r5aGw1Wm/vlXWy2A==" + }, "Zomp.SyncMethodGenerator": { "type": "Direct", "requested": "[2.0.66, )", @@ -444,6 +468,12 @@ "resolved": "1.16.0", "contentHash": "3kdIIceBPumwjw279FuiVMfVENT2cGASXJgcigdySsbX2dJB8ofUgG6i47yqF/k1qu6fvNR3csrSekZPviR6kQ==" }, + "Pure.DI": { + "type": "Direct", + "requested": "[2.5.4, )", + "resolved": "2.5.4", + "contentHash": "Q4F67gdTdbrc+9c+EjZqPiyxywXC5LVdJpKdENtHfK1XpGJ3UWPZB7rhhuqqDVbcbr1EX1r5aGw1Wm/vlXWy2A==" + }, "Zomp.SyncMethodGenerator": { "type": "Direct", "requested": "[2.0.66, )", @@ -513,6 +543,12 @@ "resolved": "1.16.0", "contentHash": "3kdIIceBPumwjw279FuiVMfVENT2cGASXJgcigdySsbX2dJB8ofUgG6i47yqF/k1qu6fvNR3csrSekZPviR6kQ==" }, + "Pure.DI": { + "type": "Direct", + "requested": "[2.5.4, )", + "resolved": "2.5.4", + "contentHash": "Q4F67gdTdbrc+9c+EjZqPiyxywXC5LVdJpKdENtHfK1XpGJ3UWPZB7rhhuqqDVbcbr1EX1r5aGw1Wm/vlXWy2A==" + }, "Zomp.SyncMethodGenerator": { "type": "Direct", "requested": "[2.0.66, )", diff --git a/tests/SharpCompress.Test/ServiceCompositionTests.cs b/tests/SharpCompress.Test/ServiceCompositionTests.cs new file mode 100644 index 00000000..71313179 --- /dev/null +++ b/tests/SharpCompress.Test/ServiceCompositionTests.cs @@ -0,0 +1,293 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using SharpCompress.Archives; +using SharpCompress.Common; +using SharpCompress.Factories; +using SharpCompress.Providers; +using SharpCompress.Providers.Default; +using SharpCompress.Readers; +using SharpCompress.Services; +using SharpCompress.Test.Mocks; +using SharpCompress.Writers; +using Xunit; + +namespace SharpCompress.Test; + +public class ServiceCompositionTests : TestBase +{ + private static ServiceComposition CreateComposition(params IFactory[] factories) => + new(new FactoryCatalog(() => factories, () => TarWrapper.Wrappers)); + + [Fact] + public void Composition_RemainsAnInternalBuildTimeDetail() + { + Type[] serviceTypes = + [ + typeof(ServiceComposition), + typeof(LibraryDefaults), + typeof(FactoryCatalog), + typeof(ArchiveService), + typeof(ReaderService), + typeof(WriterService), + typeof(ArchiveExtractor), + typeof(ArchiveFileWriter), + ]; + Assert.All( + serviceTypes, + type => + { + Assert.False(type.IsVisible); + Assert.Equal("SharpCompress.Services", type.Namespace); + } + ); + Assert.DoesNotContain( + typeof(ArchiveFactory).Assembly.GetReferencedAssemblies(), + reference => reference.Name is "Pure.DI" or "Pure.DI.Abstractions" + ); + Assert.IsType(TarWrapper.Wrappers); + } + + [Fact] + public async Task Composition_ReusesServiceRootsDuringConcurrentAccess() + { + var composition = CreateComposition(new ZipFactory()); + var other = CreateComposition(new ZipFactory()); + var roots = await Task.WhenAll( + Enumerable + .Range(0, 10) + .Select(_ => + Task.Run(() => + ( + composition.Archives, + composition.Readers, + composition.Writers, + composition.Extractor, + composition.FileWriter + ) + ) + ) + ); + Assert.All( + roots, + root => + { + Assert.Same(composition.Archives, root.Archives); + Assert.Same(composition.Readers, root.Readers); + Assert.Same(composition.Writers, root.Writers); + Assert.Same(composition.Extractor, root.Extractor); + Assert.Same(composition.FileWriter, root.FileWriter); + } + ); + Assert.NotSame(composition.Archives, other.Archives); + Assert.NotSame(composition.Readers, other.Readers); + Assert.NotSame(composition.Writers, other.Writers); + Assert.NotSame(composition.Extractor, other.Extractor); + Assert.NotSame(composition.FileWriter, other.FileWriter); + } + + [Fact] + public async Task Compositions_UseIndependentFactoriesConcurrently() + { + var zip = CreateComposition(new ZipFactory()); + var empty = CreateComposition(); + Assert.NotSame(zip.Readers, empty.Readers); + Assert.NotSame(zip.Extractor, empty.Extractor); + var path = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.zip"); + await Task.WhenAll( + Enumerable + .Range(0, 10) + .Select(async _ => + { + using var stream = File.OpenRead(path); + Assert.Equal( + ArchiveType.Zip, + zip.Archives.DetectArchive(stream)?.ContainerType + ); + Assert.Null(empty.Archives.DetectArchive(stream)); + Assert.Equal(0, stream.Position); + Assert.NotNull( + await zip.Archives.InspectArchiveAsync(stream, CancellationToken.None) + ); + Assert.Null( + await empty.Archives.InspectArchiveAsync(stream, CancellationToken.None) + ); + Assert.Equal(0, stream.Position); + using var archive = zip.Archives.OpenArchive(stream); + Assert.NotEmpty(archive.Entries); + Assert.Throws(() => + empty.Archives.OpenArchive(stream) + ); + }) + ); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Services_PreserveProvidersAndStreamOwnership(bool useAsync) + { + var services = CreateComposition(new ZipFactory()); + var provider = new TrackingDeflateProvider(); + var providers = CompressionProviderRegistry.Default.With(provider); + var writerOptions = new WriterOptions(CompressionType.Deflate) + { + Providers = providers, + LeaveStreamOpen = true, + }; + var readerOptions = new ReaderOptions { Providers = providers, LeaveStreamOpen = true }; + using var stream = new MemoryStream(); + using var payload = new MemoryStream(Encoding.UTF8.GetBytes("instance services")); + if (useAsync) + { + await using var writer = await services.Writers.OpenAsyncWriter( + stream, + ArchiveType.Zip, + writerOptions, + CancellationToken.None + ); + await writer.WriteAsync("payload.txt", payload, null, CancellationToken.None); + } + else + { + using var writer = services.Writers.OpenWriter(stream, ArchiveType.Zip, writerOptions); + writer.Write("payload.txt", payload, null); + } + Assert.True(provider.CompressionCalls > 0); + stream.Position = 0; + using var output = new MemoryStream(); + if (useAsync) + { + await using var archive = await services.Archives.OpenAsyncArchive( + stream, + readerOptions, + CancellationToken.None + ); + await foreach (var entry in archive.EntriesAsync) + { + await services.Extractor.WriteToAsync( + entry, + output, + null, + cancellationToken: CancellationToken.None + ); + } + } + else + { + using var archive = services.Archives.OpenArchive(stream, readerOptions); + services.Extractor.WriteTo(Assert.Single(archive.Entries), output, null); + } + Assert.True(provider.DecompressionCalls > 0); + Assert.Equal("instance services", Encoding.UTF8.GetString(output.ToArray())); + Assert.True(stream.CanRead); + Assert.True(output.CanWrite); + Assert.True(readerOptions.LeaveStreamOpen); + Assert.Same(providers, readerOptions.Providers); + Assert.Same(providers, writerOptions.Providers); + + stream.Position = 0; + using var forwardOnly = new ForwardOnlyStream(stream); + if (useAsync) + { + await using var reader = await services.Readers.OpenAsyncReader( + forwardOnly, + readerOptions, + CancellationToken.None + ); + Assert.True(await reader.MoveToNextEntryAsync(CancellationToken.None)); + } + else + { + using var reader = services.Readers.OpenReader(forwardOnly, readerOptions); + Assert.True(reader.MoveToNextEntry()); + } + Assert.True(forwardOnly.CanRead); + } + + [Fact] + public async Task Services_PreserveAsyncCancellation() + { + var services = CreateComposition(new ZipFactory()); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + using var stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.zip")); + await Assert.ThrowsAnyAsync(() => + services.Archives.DetectArchiveAsync(stream, cancellation.Token).AsTask() + ); + Assert.Equal(0, stream.Position); + } + + private sealed class TrackingDeflateProvider : CompressionProviderBase + { + private readonly DeflateCompressionProvider inner = new(); + public int CompressionCalls { get; private set; } + public int DecompressionCalls { get; private set; } + public override CompressionType CompressionType => CompressionType.Deflate; + public override bool SupportsCompression => true; + public override bool SupportsDecompression => true; + + public override Stream CreateCompressStream(Stream destination, int compressionLevel) + { + CompressionCalls++; + return inner.CreateCompressStream(destination, compressionLevel); + } + + public override Stream CreateDecompressStream(Stream source) + { + DecompressionCalls++; + return inner.CreateDecompressStream(source); + } + } +} + +// Legacy registration mutates process-wide state, so this collection cannot run alongside others. +[CollectionDefinition("Factory registration", DisableParallelization = true)] +public class FactoryRegistrationCollection; + +[Collection("Factory registration")] +public class FactoryRegistrationTests +{ + [Fact] + public async Task DefaultComposition_ObservesLateRegistration() + { + _ = LibraryDefaults.Composition.Archives; + var factory = new TestFactory(); + Factory.RegisterFactory(factory); + try + { + Assert.Contains(factory, Factory.Factories); + using var stream = new MemoryStream([0x49, 0x44, 0x49]); + Assert.Same(factory, ArchiveFactory.FindFactory(stream)); + Assert.Same( + factory, + await ArchiveFactory.FindFactoryAsync(stream, CancellationToken.None) + ); + } + finally + { + // Restore the legacy collection without adding a new public unregister API. + Assert.IsAssignableFrom>(Factory.Factories).Remove(factory); + } + } + + private sealed class TestFactory : Factory + { + public override string Name => "Instance DI test"; + + public override IEnumerable GetSupportedExtensions() => []; + + public override bool IsArchive(Stream stream, ReaderOptions readerOptions) => + stream.ReadByte() == 0x49 && stream.ReadByte() == 0x44 && stream.ReadByte() == 0x49; + + public override ValueTask IsArchiveAsync( + Stream stream, + ReaderOptions readerOptions, + CancellationToken cancellationToken = default + ) => new(IsArchive(stream, readerOptions)); + } +}