Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
<PackageVersion Include="Serilog.Formatting.Compact.Reader" Version="4.0.0" />
<PackageVersion Include="Serilog.Sinks.Console" Version="6.1.1" />
<PackageVersion Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageVersion Include="SharpZipLib" Version="1.4.2" />
<PackageVersion Include="SharpCompress" Version="0.50.1" />
<PackageVersion Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageVersion Include="System.Net.Http" Version="4.3.4" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Fallout.Common.IO;
using Fallout.Common.Tooling;
using Fallout.Common.Utilities;
using ICSharpCode.SharpZipLib.Zip;
using NuGet.Packaging;
using Serilog;

Expand Down Expand Up @@ -53,20 +52,7 @@ private static void ExtractPackageFiles()

packageResourceStream.Seek(offset: 0, SeekOrigin.Begin);
packageResourceStream.CopyToFile(packageFile);

using var fileStream = File.OpenRead(packageFile);
using var zipFile = new ZipFile(fileStream);

var entries = zipFile.Cast<ZipEntry>().Where(x => !x.IsDirectory);
foreach (var entry in entries)
{
var file = packageFile.Parent / entry.Name;
Directory.CreateDirectory(file.Parent);

using var entryStream = zipFile.GetInputStream(entry);
using var outputStream = File.Open(file, FileMode.Create);
entryStream.CopyTo(outputStream);
}
packageFile.UnZipTo(packageFile.Parent);
}
}

Expand Down
149 changes: 71 additions & 78 deletions src/Fallout.Utilities.IO.Compression/CompressionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
using System.IO;
using System.IO.Compression;
using System.Linq;
using Fallout.Common.Utilities.Collections;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
using ICSharpCode.SharpZipLib.Zip;
using SharpCompress.Common;
using SharpCompress.Readers;
using ZipFile = ICSharpCode.SharpZipLib.Zip.ZipFile;
using SharpCompress.Writers;
using SharpCompress.Writers.Zip;
using Fallout.Common.Utilities.Collections;

namespace Fallout.Common.IO;

Expand Down Expand Up @@ -110,14 +107,16 @@ public static void ZipTo(
filter ??= _ => true;
List<AbsolutePath> files = directory.GetFiles(depth: int.MaxValue).Where(filter).ToList();

using FileStream fileStream = File.Open(archiveFile, fileMode, FileAccess.ReadWrite);
using ZipArchive zipArchive = new(fileStream, ZipArchiveMode.Create);
using var fileStream = File.Open(archiveFile, fileMode, FileAccess.ReadWrite);
using var writer = WriterFactory.OpenWriter(
fileStream,
ArchiveType.Zip,
new ZipWriterOptions(CompressionType.Deflate, compressionLevel.ToSharpCompressCompressionLevel()));

void AddFile(AbsolutePath file)
{
RelativePath relativePath = directory.GetRelativePathTo(file);
string entryName = ZipEntry.CleanName(relativePath);
zipArchive.CreateEntryFromFile(file, entryName, compressionLevel);
var entryName = directory.GetUnixRelativePathTo(file);
writer.Write(entryName, file);
}

files.ForEach(AddFile);
Expand All @@ -131,22 +130,7 @@ void AddFile(AbsolutePath file)
/// <param name="directory">The directory into which the archive's contents are extracted.</param>
public static void UnZipTo(this AbsolutePath archiveFile, AbsolutePath directory)
{
using FileStream fileStream = File.OpenRead(archiveFile);
using ZipFile zipFile = new(fileStream);

IEnumerable<ZipEntry> entries = zipFile.Cast<ZipEntry>().Where(x => !x.IsDirectory);

void HandleEntry(ZipEntry entry)
{
AbsolutePath file = directory / entry.Name;
Directory.CreateDirectory(file.Parent.NotNull());
Comment thread
ITaluone marked this conversation as resolved.
Resolved

using Stream entryStream = zipFile.GetInputStream(entry);
using FileStream outputStream = File.Open(file, FileMode.Create);
entryStream.CopyTo(outputStream);
}

entries.ForEach(HandleEntry);
UncompressArchive(archiveFile, directory);
}

/// <summary>
Expand All @@ -160,8 +144,10 @@ public static void TarGZipTo(
this AbsolutePath baseDirectory,
AbsolutePath archiveFile,
IEnumerable<AbsolutePath> files,
FileMode fileMode = FileMode.CreateNew) =>
CompressTar(baseDirectory, archiveFile, files.ToList(), fileMode, x => new GZipOutputStream(x));
FileMode fileMode = FileMode.CreateNew)
{
CompressTar(baseDirectory, archiveFile, files.ToList(), fileMode, CompressionType.GZip);
}

/// <summary>
/// Compresses <paramref name="directory" /> into a gzip-compressed tar archive at <paramref name="archiveFile" />.
Expand Down Expand Up @@ -195,8 +181,10 @@ public static void TarBZip2To(
this AbsolutePath directory,
AbsolutePath archiveFile,
IEnumerable<AbsolutePath> files,
FileMode fileMode = FileMode.CreateNew) =>
CompressTar(directory, archiveFile, files.ToList(), fileMode, x => new BZip2OutputStream(x));
FileMode fileMode = FileMode.CreateNew)
{
CompressTar(directory, archiveFile, files.ToList(), fileMode, CompressionType.BZip2);
}

/// <summary>
/// Compresses <paramref name="directory" /> into a bzip2-compressed tar archive at <paramref name="archiveFile" />.
Expand All @@ -219,98 +207,103 @@ public static void TarBZip2To(
directory.TarBZip2To(archiveFile, files, fileMode);
}

/// <summary>
/// <summary>
/// Extracts the contents of a gzip-compressed tar archive at <paramref name="archiveFile" /> into <paramref name="directory" />.
/// Destination directory is created, and conflicting files are overwritten.
/// </summary>
/// <param name="archiveFile">The tar.gz archive file to extract.</param>
/// <param name="directory">The directory into which the archive's contents are extracted.</param>
public static void UnTarGZipTo(this AbsolutePath archiveFile, AbsolutePath directory) =>
UncompressTar(archiveFile, directory, x => new GZipInputStream(x));
public static void UnTarGZipTo(this AbsolutePath archiveFile, AbsolutePath directory)
{
UncompressArchive(archiveFile, directory);
}

/// <summary>
/// <summary>
/// Extracts the contents of a bzip2-compressed tar archive at <paramref name="archiveFile" /> into <paramref name="directory" />.
/// Destination directory is created, and conflicting files are overwritten.
/// </summary>
/// <param name="archiveFile">The tar.bz2 archive file to extract.</param>
/// <param name="directory">The directory into which the archive's contents are extracted.</param>
public static void UnTarBZip2To(this AbsolutePath archiveFile, AbsolutePath directory) =>
UncompressTar(archiveFile, directory, x => new BZip2InputStream(x));
public static void UnTarBZip2To(this AbsolutePath archiveFile, AbsolutePath directory)
{
UncompressArchive(archiveFile, directory);
}

/// <summary>
/// Extracts the contents of an xz-compressed tar archive at <paramref name="archive" /> into <paramref name="directory" />.
/// <summary>
/// Extracts the contents of an xz-compressed tar archive at <paramref name="archiveFile" /> into <paramref name="directory" />.
/// Destination directory is created, and conflicting files are skipped.
/// </summary>
/// <param name="archive">The tar.xz archive file to extract.</param>
/// <param name="archiveFile">The tar.xz archive file to extract.</param>
/// <param name="directory">The directory into which the archive's contents are extracted.</param>
public static void UnTarXzTo(this AbsolutePath archive, AbsolutePath directory)
public static void UnTarXzTo(this AbsolutePath archiveFile, AbsolutePath directory)
{
using Stream stream = File.OpenRead(archive);
using IReader reader = ReaderFactory.OpenReader(stream);

while (reader.MoveToNextEntry())
{
if (reader.Entry.IsDirectory)
{
continue;
}

reader.WriteEntryToDirectory(directory, new ExtractionOptions
{
ExtractFullPath = true,
Overwrite = true
});
}
UncompressArchive(archiveFile, directory);
}

/// <summary>
/// Compresses the given <paramref name="files" /> into a tar archive at <paramref name="archiveFile" />, wrapping the underlying
/// file stream with the compression stream produced by <paramref name="outputStreamFactory" />.
/// Compresses the given <paramref name="files" /> into a tar archive at <paramref name="archiveFile" /> using
/// <paramref name="compressionType" />.
/// </summary>
/// <param name="baseDirectory">The base directory used to compute the relative entry names of the archived files.</param>
/// <param name="archiveFile">The archive file to create.</param>
/// <param name="files">The files to add to the archive.</param>
/// <param name="fileMode">The <see cref="FileMode" /> used to open the archive file.</param>
/// <param name="outputStreamFactory">A factory that wraps the raw archive file stream with the desired compression stream.</param>
/// <param name="compressionType">The compression type to use for the archive.</param>
private static void CompressTar(
AbsolutePath baseDirectory,
AbsolutePath archiveFile,
IReadOnlyCollection<AbsolutePath> files,
FileMode fileMode,
Func<Stream, Stream> outputStreamFactory)
CompressionType compressionType)
{
archiveFile.Parent.CreateDirectory();

using FileStream fileStream = File.Open(archiveFile, fileMode, FileAccess.ReadWrite);
using Stream outputStream = outputStreamFactory(fileStream);
using TarArchive tarArchive = TarArchive.CreateOutputTarArchive(outputStream);
using var fileStream = File.Open(archiveFile, fileMode, FileAccess.ReadWrite);
using var writer = WriterFactory.OpenWriter(fileStream, ArchiveType.Tar, new WriterOptions(compressionType));

void AddFile(AbsolutePath file)
{
TarEntry entry = TarEntry.CreateEntryFromFile(file);
entry.Name = baseDirectory.GetUnixRelativePathTo(file);

tarArchive.WriteEntry(entry, false);
var entryName = baseDirectory.GetUnixRelativePathTo(file);
// ReSharper disable once AccessToDisposedClosure
writer.Write(entryName, file);
}

files.ForEach(AddFile);
}

/// <summary>
/// Extracts the contents of a tar archive at <paramref name="archiveFile" /> into <paramref name="directory" />, wrapping the
/// underlying file stream with the decompression stream produced by <paramref name="inputStreamFactory" />.
private static SharpCompress.Compressors.Deflate.CompressionLevel ToSharpCompressCompressionLevel(
this CompressionLevel compressionLevel)
{
return compressionLevel switch
{
CompressionLevel.NoCompression => SharpCompress.Compressors.Deflate.CompressionLevel.None,
CompressionLevel.Fastest => SharpCompress.Compressors.Deflate.CompressionLevel.BestSpeed,
CompressionLevel.Optimal => SharpCompress.Compressors.Deflate.CompressionLevel.Default,
_ => SharpCompress.Compressors.Deflate.CompressionLevel.BestCompression
};
}

/// <summary>
/// Extracts the contents of an archive at <paramref name="archiveFile" /> into <paramref name="directory" />.
/// </summary>
/// <param name="archiveFile">The archive file to extract.</param>
/// <param name="directory">The directory into which the archive's contents are extracted.</param>
/// <param name="inputStreamFactory">A factory that wraps the raw archive file stream with the desired decompression stream.</param>
private static void UncompressTar(AbsolutePath archiveFile, AbsolutePath directory, Func<Stream, Stream> inputStreamFactory)
private static void UncompressArchive(AbsolutePath archiveFile, AbsolutePath directory)
{
using FileStream fileStream = File.OpenRead(archiveFile);
using Stream inputStream = inputStreamFactory(fileStream);
using TarArchive tarArchive = TarArchive.CreateInputTarArchive(inputStream, null);
using var fileStream = File.OpenRead(archiveFile);
using var reader = ReaderFactory.OpenReader(fileStream);

directory.CreateDirectory();

tarArchive.ExtractContents(directory);
while (reader.MoveToNextEntry())
{
if (reader.Entry.IsDirectory)
continue;

reader.WriteEntryToDirectory(directory, new ExtractionOptions
{
ExtractFullPath = true,
Overwrite = true
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="SharpZipLib" />
<PackageReference Include="SharpCompress" />
</ItemGroup>

Expand Down
7 changes: 1 addition & 6 deletions tests/Fallout.Utilities.Specs/IO/CompressionTasksSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,12 @@

namespace Fallout.Common.Specs;

public class CompressionTasksSpecs : FileSystemDependentSpecs
public class CompressionTasksSpecs(ITestOutputHelper testOutputHelper) : FileSystemDependentSpecs(testOutputHelper)
{
private AbsolutePath RootFile => TestTempDirectory / "root-file";

private AbsolutePath NestedFile => TestTempDirectory / "a" / "b" / "c" / "nested-file";

public CompressionTasksSpecs(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
}

[Theory]
[InlineData("archive.zip")]
[InlineData("archive.tar.gz")]
Expand Down
66 changes: 66 additions & 0 deletions tests/Fallout.Utilities.Specs/IO/PathCompressionSpecs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System;
using System.Linq;
using Fallout.Common.IO;
using FluentAssertions;
using Xunit;

namespace Fallout.Common.Specs;

public class PathCompressionSpecs : IDisposable
{
private readonly AbsolutePath testDirectory = AbsolutePath.Temp();
private readonly AbsolutePath uncompressDirectory = AbsolutePath.Temp();
private const string ExpectedHash = "516e16d7450ea2d4f75e9cad5878d3fe";
private readonly Random random;

public PathCompressionSpecs()
{
testDirectory.CreateDirectory();
random = new Random(53463464);

GenerateTestFiles(testDirectory, 100, 5);
}

[Theory]
[InlineData("archive.zip")]
[InlineData("archive.tar.bz2")]
[InlineData("archive.tar.gz")]
public void A_directory_has_the_same_hash_from_the_old_implementation(string archiveFile)
{
// Arrange
var archivePath = AbsolutePath.Temp() / archiveFile;
testDirectory.CompressTo(archivePath);

// Act
archivePath.UncompressTo(uncompressDirectory);

// Assert
var hash = uncompressDirectory.GetDirectoryHash();
hash.Should().Be(ExpectedHash);
}

private void GenerateTestFiles(AbsolutePath absolutePath, int fileCount, int maximumNestingLevel)
{
for (var i = 0; i < fileCount; i++)
{
var nestingLevel = random.Next(maximumNestingLevel + 1);
var directory = Enumerable.Range(0, nestingLevel)
.Aggregate(absolutePath, (current, _) => current / $"dir-{random.Next(int.MaxValue)}");

if (random.Next() % 2344 == 0)
{
directory.CreateDirectory();
continue;
}

var file = directory / $"file-{random.Next(int.MaxValue)}.txt";
file.WriteAllText(random.Next().ToString(), eofLineBreak: false);
}
}

public void Dispose()
{
testDirectory.DeleteDirectory();
uncompressDirectory.DeleteDirectory();
}
}
Loading