Files

74 lines
2.8 KiB
C#
Raw Permalink Normal View History

2025-09-12 09:02:03 -04:00
using System;
using System.IO;
2026-08-27 13:56:09 -04:00
using Nanook.GrindCore;
using Nanook.GrindCore.DeflateZLib;
2025-09-26 13:06:18 -04:00
using SabreTools.Data.Models.GZIP;
2025-10-27 22:43:56 -04:00
using SabreTools.IO.Extensions;
2025-09-12 09:02:03 -04:00
2026-03-18 16:37:59 -04:00
namespace SabreTools.Wrappers
2025-09-12 09:02:03 -04:00
{
public partial class GZip : IExtractable
{
/// <inheritdoc/>
public bool Extract(string outputDirectory, bool includeDebug)
{
// Ensure there is data to extract
2026-01-25 14:30:18 -05:00
if (Header is null || DataOffset < 0)
2025-09-12 09:02:03 -04:00
{
if (includeDebug) Console.Error.WriteLine("Invalid archive detected, skipping...");
return false;
}
// Ensure that DEFLATE is being used
if (Header.CompressionMethod != CompressionMethod.Deflate)
{
if (includeDebug) Console.Error.WriteLine($"Invalid compression method {Header.CompressionMethod} detected, only DEFLATE is supported. Skipping...");
return false;
}
try
{
// Seek to the start of the compressed data
2025-10-27 22:43:56 -04:00
long offset = _dataSource.SeekIfPossible(DataOffset, SeekOrigin.Begin);
2025-09-12 09:02:03 -04:00
if (offset != DataOffset)
{
if (includeDebug) Console.Error.WriteLine($"Could not seek to compressed data at {DataOffset}");
return false;
}
// Ensure directory separators are consistent
string filename = Header.OriginalFileName
2026-01-25 14:32:49 -05:00
?? (Filename is not null ? Path.GetFileName(Filename).Replace(".gz", string.Empty) : null)
2025-09-12 09:02:03 -04:00
?? $"extracted_file";
filename = filename.TrimStart(['\\', '/']);
2025-09-12 09:02:03 -04:00
if (Path.DirectorySeparatorChar == '\\')
filename = filename.Replace('/', '\\');
else if (Path.DirectorySeparatorChar == '/')
filename = filename.Replace('\\', '/');
// Ensure the full output directory exists
filename = Path.Combine(outputDirectory, filename);
var directoryName = Path.GetDirectoryName(filename);
2026-01-25 14:32:49 -05:00
if (directoryName is not null && !Directory.Exists(directoryName))
2025-09-12 09:02:03 -04:00
Directory.CreateDirectory(directoryName);
// Open the source as a DEFLATE stream
2026-08-27 13:56:09 -04:00
var deflateStream = new DeflateStream(_dataSource, new CompressionOptions { LeaveOpen = true, Type = CompressionType.Decompress});
2025-09-12 09:02:03 -04:00
// Write the file
using var fs = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.None);
2026-03-24 19:17:25 -04:00
deflateStream.BlockCopy(fs);
2025-09-12 09:02:03 -04:00
fs.Flush();
return true;
}
catch (Exception ex)
{
if (includeDebug) Console.Error.WriteLine(ex);
return false;
}
}
}
}