mirror of
https://github.com/adamhathcock/sharpcompress.git
synced 2026-11-17 01:41:02 +00:00
Refactor factory workflows into internal Pure.DI services
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="8.0.0" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.10.1" />
|
||||
<PackageVersion Include="Mono.Posix.NETStandard" Version="1.0.0" />
|
||||
<PackageVersion Include="Pure.DI" Version="2.5.4" />
|
||||
<PackageVersion Include="SimpleExec" Version="13.1.0" />
|
||||
<PackageVersion Include="System.Text.Encoding.CodePages" Version="10.0.12" />
|
||||
<PackageVersion Include="xunit.v3" Version="3.2.2" />
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<IArchiveFactory>(stream, readerOptions)
|
||||
.OpenArchive(stream, readerOptions);
|
||||
}
|
||||
private static ArchiveService Service => LibraryDefaults.Composition.Archives;
|
||||
|
||||
public static IWritableArchive<TOptions> CreateArchive<TOptions>()
|
||||
where TOptions : IWriterOptions
|
||||
{
|
||||
var factory = Factory
|
||||
.Factories.OfType<IWritableArchiveFactory<TOptions>>()
|
||||
.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<IArchiveFactory>(fileInfo, options).OpenArchive(fileInfo, options);
|
||||
}
|
||||
public static IArchive OpenArchive(FileInfo fileInfo, ReaderOptions? options = null) =>
|
||||
Service.OpenArchive(fileInfo, options);
|
||||
|
||||
public static IArchive OpenArchive(
|
||||
IReadOnlyList<FileInfo> 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<Stream> streams,
|
||||
ReaderOptions? options = null
|
||||
) => Service.OpenArchive(streams, options);
|
||||
|
||||
fileInfo.NotNull(nameof(fileInfo));
|
||||
options ??= ReaderOptions.ForFilePath;
|
||||
public static IWritableArchive<TOptions> CreateArchive<TOptions>()
|
||||
where TOptions : IWriterOptions => Service.CreateArchive<TOptions>();
|
||||
|
||||
return FindFactory<IMultiArchiveFactory>(fileInfo, options)
|
||||
.OpenArchive(filesArray, options);
|
||||
}
|
||||
public static ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
Stream stream,
|
||||
ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.OpenAsyncArchive(stream, readerOptions, cancellationToken);
|
||||
|
||||
public static IArchive OpenArchive(IReadOnlyList<Stream> streams, ReaderOptions? options = null)
|
||||
{
|
||||
var streamsArray = streams.RequireReadable().RequireSeekable().ToList();
|
||||
if (streamsArray.Count == 0)
|
||||
{
|
||||
throw new ArchiveOperationException("No streams");
|
||||
}
|
||||
public static ValueTask<IAsyncArchive> 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<IAsyncArchive> OpenAsyncArchive(
|
||||
FileInfo fileInfo,
|
||||
ReaderOptions? options = null,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.OpenAsyncArchive(fileInfo, options, cancellationToken);
|
||||
|
||||
firstStream.NotNull(nameof(firstStream));
|
||||
options ??= ReaderOptions.ForExternalStream;
|
||||
public static ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
IReadOnlyList<FileInfo> fileInfos,
|
||||
ReaderOptions? options = null,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.OpenAsyncArchive(fileInfos, options, cancellationToken);
|
||||
|
||||
return FindFactory<IMultiArchiveFactory>(firstStream, options)
|
||||
.OpenArchive(streamsArray, options);
|
||||
}
|
||||
public static ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
IReadOnlyList<Stream> 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<T>(string filePath)
|
||||
where T : IFactory
|
||||
{
|
||||
filePath.NotNullOrEmpty(nameof(filePath));
|
||||
using Stream stream = File.OpenRead(filePath);
|
||||
return FindFactory<T>(stream);
|
||||
}
|
||||
where T : IFactory => Service.FindFactory<T>(filePath);
|
||||
|
||||
public static T FindFactory<T>(FileInfo finfo)
|
||||
where T : IFactory
|
||||
{
|
||||
finfo.NotNull(nameof(finfo));
|
||||
using Stream stream = finfo.OpenRead();
|
||||
return FindFactory<T>(stream);
|
||||
}
|
||||
where T : IFactory => Service.FindFactory<T>(finfo);
|
||||
|
||||
public static T FindFactory<T>(Stream stream)
|
||||
where T : IFactory => FindFactory<T>(stream, ReaderOptions.ForExternalStream);
|
||||
where T : IFactory => Service.FindFactory<T>(stream);
|
||||
|
||||
public static bool IsArchive(string filePath, out ArchiveType? type)
|
||||
{
|
||||
return IsArchive(filePath, ReaderOptions.ForFilePath, out type);
|
||||
}
|
||||
internal static ValueTask<T> FindFactoryAsync<T>(
|
||||
string filePath,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
where T : IFactory => Service.FindFactoryAsync<T>(filePath, cancellationToken);
|
||||
|
||||
internal static ValueTask<T> FindFactoryAsync<T>(
|
||||
FileInfo fileInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
where T : IFactory => Service.FindFactoryAsync<T>(fileInfo, cancellationToken);
|
||||
|
||||
internal static ValueTask<T> FindFactoryAsync<T>(
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
where T : IFactory => Service.FindFactoryAsync<T>(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);
|
||||
}
|
||||
/// <summary>Identify the archive without enumerating its entries.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
string filePath,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.DetectArchiveAsync(filePath, cancellationToken);
|
||||
|
||||
public static IEnumerable<string> GetFileParts(string part1)
|
||||
{
|
||||
part1.NotNullOrEmpty(nameof(part1));
|
||||
return GetFileParts(new FileInfo(part1)).Select(a => a.FullName);
|
||||
}
|
||||
/// <summary>Identify the archive without enumerating its entries.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
string filePath,
|
||||
ReaderOptions? readerOptions,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.DetectArchiveAsync(filePath, readerOptions, cancellationToken);
|
||||
|
||||
public static IEnumerable<FileInfo> GetFileParts(FileInfo part1)
|
||||
{
|
||||
part1.NotNull(nameof(part1));
|
||||
yield return part1;
|
||||
/// <summary>Identify the archive without enumerating its entries. Restore the stream position.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.DetectArchiveAsync(stream, cancellationToken);
|
||||
|
||||
foreach (var factory in Factory.Factories.OfType<IFactory>())
|
||||
{
|
||||
var i = 1;
|
||||
var part = factory.GetFilePart(i++, part1);
|
||||
/// <summary>Identify the archive without enumerating its entries. Restore the stream position.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveDetection?> 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;
|
||||
}
|
||||
/// <summary>Inspect archive metadata.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
string filePath,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.InspectArchiveAsync(filePath, cancellationToken);
|
||||
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>Inspect archive metadata.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
string filePath,
|
||||
ReaderOptions? readerOptions,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.InspectArchiveAsync(filePath, readerOptions, cancellationToken);
|
||||
|
||||
/// <summary>Inspect archive metadata, leaving the stream open at its original position.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.InspectArchiveAsync(stream, cancellationToken);
|
||||
|
||||
/// <summary>Inspect archive metadata, leaving the stream open at its original position.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
Stream stream,
|
||||
ReaderOptions? readerOptions,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.InspectArchiveAsync(stream, readerOptions, cancellationToken);
|
||||
|
||||
/// <summary>Inspect multipart archive metadata.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
IReadOnlyList<FileInfo> fileInfos,
|
||||
ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.InspectArchiveAsync(fileInfos, readerOptions, cancellationToken);
|
||||
|
||||
/// <summary>Inspect multipart archive metadata, leaving the streams open at their original positions.</summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
IReadOnlyList<Stream> streams,
|
||||
ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default
|
||||
) => Service.InspectArchiveAsync(streams, readerOptions, cancellationToken);
|
||||
|
||||
public static IEnumerable<string> GetFileParts(string part1) => Service.GetFileParts(part1);
|
||||
|
||||
public static IEnumerable<FileInfo> GetFileParts(FileInfo part1) => Service.GetFileParts(part1);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <param name="archiveEntry">The archive entry to extract.</param>
|
||||
extension(IArchiveEntry archiveEntry)
|
||||
{
|
||||
@@ -64,66 +67,17 @@ public static partial class IArchiveEntryExtensions
|
||||
ExtractionOptions? options = null,
|
||||
IProgress<ProgressReport>? 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<ProgressReport>? 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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
/// <summary>
|
||||
/// Opens a Reader for Non-seeking usage
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
public static IReader OpenReader(Stream stream, ReaderOptions? options = null)
|
||||
{
|
||||
stream.RequireReadable();
|
||||
options ??= ReaderOptions.ForExternalStream;
|
||||
/// <summary>Open a reader for forward-only usage.</summary>
|
||||
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<IAsyncReader> 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<IAsyncReader> OpenAsyncReader(
|
||||
FileInfo fileInfo,
|
||||
ReaderOptions? options = null,
|
||||
CancellationToken cancellationToken = default
|
||||
) => LibraryDefaults.Composition.Readers.OpenAsyncReader(fileInfo, options, cancellationToken);
|
||||
|
||||
var factories = Factories.Factory.Factories.OfType<Factories.Factory>();
|
||||
|
||||
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<IAsyncReader> OpenAsyncReader(
|
||||
Stream stream,
|
||||
ReaderOptions? options = null,
|
||||
CancellationToken cancellationToken = default
|
||||
) => LibraryDefaults.Composition.Readers.OpenAsyncReader(stream, options, cancellationToken);
|
||||
}
|
||||
|
||||
80
src/SharpCompress/Services/ArchiveExtractor.cs
Normal file
80
src/SharpCompress/Services/ArchiveExtractor.cs
Normal file
@@ -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<ProgressReport>? 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<ProgressReport>? 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
92
src/SharpCompress/Services/ArchiveFileWriter.cs
Normal file
92
src/SharpCompress/Services/ArchiveFileWriter.cs
Normal file
@@ -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<string, bool>? 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<string, bool>? 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<IAsyncArchive> OpenAsyncArchive(
|
||||
public async ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
Stream stream,
|
||||
ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -28,7 +29,7 @@ public static partial class ArchiveFactory
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
public ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
string filePath,
|
||||
ReaderOptions? options = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -42,7 +43,7 @@ public static partial class ArchiveFactory
|
||||
);
|
||||
}
|
||||
|
||||
public static async ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
public async ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
FileInfo fileInfo,
|
||||
ReaderOptions? options = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -57,7 +58,7 @@ public static partial class ArchiveFactory
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static async ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
public async ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
IReadOnlyList<FileInfo> fileInfos,
|
||||
ReaderOptions? options = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -91,7 +92,7 @@ public static partial class ArchiveFactory
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static async ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
public async ValueTask<IAsyncArchive> OpenAsyncArchive(
|
||||
IReadOnlyList<Stream> streams,
|
||||
ReaderOptions? options = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Identifies the archive at the given file path without enumerating its entries.
|
||||
@@ -20,7 +21,7 @@ public static partial class ArchiveFactory
|
||||
/// <param name="filePath">Path to the archive file.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
public async ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
string filePath,
|
||||
CancellationToken cancellationToken = default
|
||||
) =>
|
||||
@@ -34,7 +35,7 @@ public static partial class ArchiveFactory
|
||||
/// <param name="readerOptions">Options controlling archive detection.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
public async ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
string filePath,
|
||||
ReaderOptions? readerOptions,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -56,7 +57,7 @@ public static partial class ArchiveFactory
|
||||
/// <param name="stream">A readable and seekable stream positioned at the start of the archive.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
public async ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
) =>
|
||||
@@ -70,7 +71,7 @@ public static partial class ArchiveFactory
|
||||
/// <param name="readerOptions">Options controlling archive detection.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
public async ValueTask<ArchiveDetection?> DetectArchiveAsync(
|
||||
Stream stream,
|
||||
ReaderOptions? readerOptions,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -87,7 +88,7 @@ public static partial class ArchiveFactory
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static ValueTask<T> FindFactoryAsync<T>(
|
||||
internal ValueTask<T> FindFactoryAsync<T>(
|
||||
string filePath,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
@@ -97,7 +98,7 @@ public static partial class ArchiveFactory
|
||||
return FindFactoryAsync<T>(new FileInfo(filePath), cancellationToken);
|
||||
}
|
||||
|
||||
internal static async ValueTask<T> FindFactoryAsync<T>(
|
||||
internal async ValueTask<T> FindFactoryAsync<T>(
|
||||
FileInfo fileInfo,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
@@ -109,7 +110,7 @@ public static partial class ArchiveFactory
|
||||
}
|
||||
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
private static async ValueTask<T> FindFactoryAsync<T>(
|
||||
private async ValueTask<T> FindFactoryAsync<T>(
|
||||
FileInfo fileInfo,
|
||||
ReaderOptions readerOptions,
|
||||
CancellationToken cancellationToken
|
||||
@@ -122,7 +123,7 @@ public static partial class ArchiveFactory
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async ValueTask<T> FindFactoryAsync<T>(
|
||||
internal async ValueTask<T> FindFactoryAsync<T>(
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
@@ -140,7 +141,7 @@ public static partial class ArchiveFactory
|
||||
}
|
||||
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
private static async ValueTask<T> FindFactoryAsync<T>(
|
||||
private async ValueTask<T> FindFactoryAsync<T>(
|
||||
Stream stream,
|
||||
ReaderOptions readerOptions,
|
||||
CancellationToken cancellationToken
|
||||
@@ -157,7 +158,7 @@ public static partial class ArchiveFactory
|
||||
return typedFactory;
|
||||
}
|
||||
|
||||
var extensions = string.Join(", ", Factory.Factories.OfType<T>().Select(item => item.Name));
|
||||
var extensions = string.Join(", ", catalog.Factories.OfType<T>().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.
|
||||
/// </summary>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
private static async ValueTask<IFactory?> TryFindFactoryAsync(
|
||||
private async ValueTask<IFactory?> 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<ArchiveDetection?> TryDetectArchiveAsync(
|
||||
private async ValueTask<ArchiveDetection?> 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<CompressionType?> TryDetectCompressedTarAsync(
|
||||
private async ValueTask<CompressionType?> 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();
|
||||
@@ -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)
|
||||
{
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Collects metadata for the archive at the given file path.
|
||||
@@ -26,7 +27,7 @@ public static partial class ArchiveFactory
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Archive metadata, or <see langword="null"/> when the file is not a supported archive.</returns>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
public async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
string filePath,
|
||||
CancellationToken cancellationToken = default
|
||||
) =>
|
||||
@@ -41,7 +42,7 @@ public static partial class ArchiveFactory
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Archive metadata, or <see langword="null"/> when the file is not a supported archive.</returns>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
public async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
string filePath,
|
||||
ReaderOptions? readerOptions,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -76,7 +77,7 @@ public static partial class ArchiveFactory
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Archive metadata, or <see langword="null"/> when the stream is not a supported archive.</returns>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
public async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
Stream stream,
|
||||
CancellationToken cancellationToken = default
|
||||
) =>
|
||||
@@ -92,7 +93,7 @@ public static partial class ArchiveFactory
|
||||
/// <returns>Archive metadata, or <see langword="null"/> when the stream is not a supported archive.</returns>
|
||||
/// <remarks>The supplied stream remains open and is restored to its original position.</remarks>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
public async ValueTask<ArchiveInformation?> 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
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Archive metadata, or <see langword="null"/> when the files are not a supported archive.</returns>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
public async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
IReadOnlyList<FileInfo> fileInfos,
|
||||
ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -295,7 +296,7 @@ public static partial class ArchiveFactory
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Archive metadata, or <see langword="null"/> when the streams are not a supported archive.</returns>
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
public static async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
public async ValueTask<ArchiveInformation?> InspectArchiveAsync(
|
||||
IReadOnlyList<Stream> streams,
|
||||
ReaderOptions? readerOptions = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -597,7 +598,7 @@ public static partial class ArchiveFactory
|
||||
}
|
||||
|
||||
[Zomp.SyncMethodGenerator.CreateSyncVersion]
|
||||
private static async ValueTask<ArchiveDetection?> RedetectArchiveAsync(
|
||||
private async ValueTask<ArchiveDetection?> RedetectArchiveAsync(
|
||||
Stream stream,
|
||||
long startPosition,
|
||||
ReaderOptions options,
|
||||
@@ -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);
|
||||
227
src/SharpCompress/Services/ArchiveService.cs
Normal file
227
src/SharpCompress/Services/ArchiveService.cs
Normal file
@@ -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<IArchiveFactory>(stream, readerOptions)
|
||||
.OpenArchive(stream, readerOptions);
|
||||
}
|
||||
|
||||
public IWritableArchive<TOptions> CreateArchive<TOptions>()
|
||||
where TOptions : IWriterOptions
|
||||
{
|
||||
var factory = catalog
|
||||
.Factories.OfType<IWritableArchiveFactory<TOptions>>()
|
||||
.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<IArchiveFactory>(fileInfo, options).OpenArchive(fileInfo, options);
|
||||
}
|
||||
|
||||
public IArchive OpenArchive(IReadOnlyList<FileInfo> 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<IMultiArchiveFactory>(fileInfo, options)
|
||||
.OpenArchive(filesArray, options);
|
||||
}
|
||||
|
||||
public IArchive OpenArchive(IReadOnlyList<Stream> 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<IMultiArchiveFactory>(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<T>(string filePath)
|
||||
where T : IFactory
|
||||
{
|
||||
filePath.NotNullOrEmpty(nameof(filePath));
|
||||
using Stream stream = File.OpenRead(filePath);
|
||||
return FindFactory<T>(stream);
|
||||
}
|
||||
|
||||
public T FindFactory<T>(FileInfo finfo)
|
||||
where T : IFactory
|
||||
{
|
||||
finfo.NotNull(nameof(finfo));
|
||||
using Stream stream = finfo.OpenRead();
|
||||
return FindFactory<T>(stream);
|
||||
}
|
||||
|
||||
public T FindFactory<T>(Stream stream)
|
||||
where T : IFactory => FindFactory<T>(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<string> GetFileParts(string part1)
|
||||
{
|
||||
part1.NotNullOrEmpty(nameof(part1));
|
||||
return GetFileParts(new FileInfo(part1)).Select(a => a.FullName);
|
||||
}
|
||||
|
||||
public IEnumerable<FileInfo> GetFileParts(FileInfo part1)
|
||||
{
|
||||
part1.NotNull(nameof(part1));
|
||||
yield return part1;
|
||||
|
||||
foreach (var factory in catalog.Factories.OfType<IFactory>())
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
15
src/SharpCompress/Services/FactoryCatalog.cs
Normal file
15
src/SharpCompress/Services/FactoryCatalog.cs
Normal file
@@ -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<IEnumerable<IFactory>> factories,
|
||||
Func<IEnumerable<TarWrapper>> wrappers
|
||||
)
|
||||
{
|
||||
public IEnumerable<IFactory> Factories => factories();
|
||||
public IEnumerable<TarWrapper> Wrappers => wrappers();
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Opens a Reader from a filepath asynchronously
|
||||
@@ -18,7 +19,7 @@ public static partial class ReaderFactory
|
||||
/// <param name="options"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public static ValueTask<IAsyncReader> OpenAsyncReader(
|
||||
public ValueTask<IAsyncReader> OpenAsyncReader(
|
||||
string filePath,
|
||||
ReaderOptions? options = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -39,7 +40,7 @@ public static partial class ReaderFactory
|
||||
/// <param name="options"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public static async ValueTask<IAsyncReader> OpenAsyncReader(
|
||||
public async ValueTask<IAsyncReader> 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<IAsyncReader> OpenAsyncReader(
|
||||
public async ValueTask<IAsyncReader> 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<Factory>();
|
||||
var factories = catalog.Factories.OfType<Factory>();
|
||||
|
||||
Factory? testedFactory = null;
|
||||
if (!string.IsNullOrWhiteSpace(options.ExtensionHint))
|
||||
89
src/SharpCompress/Services/ReaderService.cs
Normal file
89
src/SharpCompress/Services/ReaderService.cs
Normal file
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a Reader for Non-seeking usage
|
||||
/// </summary>
|
||||
/// <param name="stream"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
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>();
|
||||
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
40
src/SharpCompress/Services/ServiceComposition.cs
Normal file
40
src/SharpCompress/Services/ServiceComposition.cs
Normal file
@@ -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<FactoryCatalog>("catalog")
|
||||
.Bind()
|
||||
.As(Lifetime.Singleton)
|
||||
.To<ReaderService>()
|
||||
.Bind()
|
||||
.As(Lifetime.Singleton)
|
||||
.To<ArchiveService>()
|
||||
.Bind()
|
||||
.As(Lifetime.Singleton)
|
||||
.To<WriterService>()
|
||||
.Bind()
|
||||
.As(Lifetime.Singleton)
|
||||
.To<ArchiveExtractor>()
|
||||
.Bind()
|
||||
.As(Lifetime.Singleton)
|
||||
.To<ArchiveFileWriter>()
|
||||
.Root<ArchiveService>("Archives")
|
||||
.Root<ReaderService>("Readers")
|
||||
.Root<WriterService>("Writers")
|
||||
.Root<ArchiveExtractor>("Extractor")
|
||||
.Root<ArchiveFileWriter>("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));
|
||||
}
|
||||
120
src/SharpCompress/Services/WriterService.cs
Normal file
120
src/SharpCompress/Services/WriterService.cs
Normal file
@@ -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<IAsyncWriter> 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<IAsyncWriter> 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<IWriterFactory>()
|
||||
.FirstOrDefault(item => item.KnownArchiveType == archiveType);
|
||||
|
||||
if (factory != null)
|
||||
{
|
||||
return factory.OpenWriter(stream, writerOptions);
|
||||
}
|
||||
|
||||
throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a Writer asynchronously.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to write to.</param>
|
||||
/// <param name="archiveType">The archive type.</param>
|
||||
/// <param name="writerOptions">Writer options.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A <see cref="ValueTask{TResult}"/> containing the async writer.</returns>
|
||||
public async ValueTask<IAsyncWriter> OpenAsyncWriter(
|
||||
Stream stream,
|
||||
ArchiveType archiveType,
|
||||
IWriterOptions writerOptions,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
stream.RequireWritable();
|
||||
|
||||
var factory = catalog
|
||||
.Factories.OfType<IWriterFactory>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@
|
||||
<PackageReference Include="System.Text.Encoding.CodePages" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Pure.DI" PrivateAssets="all" />
|
||||
<None Include="..\..\README.md" Pack="true" PackagePath="\" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -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<string, bool>? 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<string, bool>? 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,
|
||||
|
||||
@@ -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<IAsyncWriter> OpenAsyncWriter(
|
||||
public static IWriter OpenWriter(
|
||||
Stream stream,
|
||||
ArchiveType archiveType,
|
||||
IWriterOptions writerOptions
|
||||
) => LibraryDefaults.Composition.Writers.OpenWriter(stream, archiveType, writerOptions);
|
||||
|
||||
public static ValueTask<IAsyncWriter> 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<IAsyncWriter> OpenAsyncWriter(
|
||||
public static ValueTask<IAsyncWriter> 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<IWriterFactory>()
|
||||
.FirstOrDefault(item => item.KnownArchiveType == archiveType);
|
||||
|
||||
if (factory != null)
|
||||
{
|
||||
return factory.OpenWriter(stream, writerOptions);
|
||||
}
|
||||
|
||||
throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a Writer asynchronously.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream to write to.</param>
|
||||
/// <param name="archiveType">The archive type.</param>
|
||||
/// <param name="writerOptions">Writer options.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A <see cref="ValueTask{TResult}"/> containing the async writer.</returns>
|
||||
public static async ValueTask<IAsyncWriter> OpenAsyncWriter(
|
||||
public static ValueTask<IAsyncWriter> OpenAsyncWriter(
|
||||
Stream stream,
|
||||
ArchiveType archiveType,
|
||||
IWriterOptions writerOptions,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
stream.RequireWritable();
|
||||
|
||||
var factory = Factories
|
||||
.Factory.Factories.OfType<IWriterFactory>()
|
||||
.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
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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, )",
|
||||
|
||||
293
tests/SharpCompress.Test/ServiceCompositionTests.cs
Normal file
293
tests/SharpCompress.Test/ServiceCompositionTests.cs
Normal file
@@ -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[]>(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<ArchiveOperationException>(() =>
|
||||
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<OperationCanceledException>(() =>
|
||||
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<IFactory>(stream));
|
||||
Assert.Same(
|
||||
factory,
|
||||
await ArchiveFactory.FindFactoryAsync<IFactory>(stream, CancellationToken.None)
|
||||
);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Restore the legacy collection without adding a new public unregister API.
|
||||
Assert.IsAssignableFrom<ICollection<Factory>>(Factory.Factories).Remove(factory);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TestFactory : Factory
|
||||
{
|
||||
public override string Name => "Instance DI test";
|
||||
|
||||
public override IEnumerable<string> GetSupportedExtensions() => [];
|
||||
|
||||
public override bool IsArchive(Stream stream, ReaderOptions readerOptions) =>
|
||||
stream.ReadByte() == 0x49 && stream.ReadByte() == 0x44 && stream.ReadByte() == 0x49;
|
||||
|
||||
public override ValueTask<bool> IsArchiveAsync(
|
||||
Stream stream,
|
||||
ReaderOptions readerOptions,
|
||||
CancellationToken cancellationToken = default
|
||||
) => new(IsArchive(stream, readerOptions));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user