Skip to content

Commit

Permalink
More advanced debugging
Browse files Browse the repository at this point in the history
  • Loading branch information
fpseverino committed Sep 9, 2024
1 parent 61b9d18 commit 59ea45f
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 92 deletions.
28 changes: 5 additions & 23 deletions Sources/Zip/ArchiveFile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@ extension Zip {
compression: ZipCompression = .DefaultCompression,
progress: ((_ progress: Double) -> ())? = nil
) throws {
let destinationPath = zipFilePath.path

// Progress handler set up
var currentPosition: Int = 0
var totalSize: Int = 0
Expand All @@ -71,20 +69,14 @@ extension Zip {
progressTracker.kind = ProgressKind.file

// Begin Zipping
let zip = zipOpen(destinationPath, APPEND_STATUS_CREATE)
let zip = zipOpen(zipFilePath.path, APPEND_STATUS_CREATE)

for archiveFile in archiveFiles {
// Skip empty data
if archiveFile.data.isEmpty {
continue
}
if archiveFile.data.isEmpty { continue }

// Setup the zip file info
var zipInfo = zip_fileinfo(
dos_date: 0,
internal_fa: 0,
external_fa: 0
)
var zipInfo = zip_fileinfo(dos_date: 0, internal_fa: 0, external_fa: 0)

if let modifiedTime = archiveFile.modifiedTime {
zipInfo.dos_date = modifiedTime.dosDate
Expand All @@ -94,15 +86,8 @@ extension Zip {
zipOpenNewFileInZip3(
zip, archiveFile.filename, &zipInfo,
nil, 0, nil, 0,
nil,
UInt16(Z_DEFLATED),
compression.minizipCompression,
0,
-MAX_WBITS,
DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY,
password,
0
nil, UInt16(Z_DEFLATED), compression.minizipCompression, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
password, 0
)
let _ = archiveFile.data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
zipWriteInFileInZip(zip, bytes.baseAddress, UInt32(archiveFile.data.count))
Expand All @@ -111,11 +96,9 @@ extension Zip {

// Update progress handler
currentPosition += archiveFile.data.count

if let progressHandler = progress {
progressHandler((Double(currentPosition/totalSize)))
}

progressTracker.completedUnitCount = Int64(currentPosition)
}

Expand All @@ -125,7 +108,6 @@ extension Zip {
if let progressHandler = progress {
progressHandler(1.0)
}

progressTracker.completedUnitCount = Int64(totalSize)
}
}
7 changes: 1 addition & 6 deletions Sources/Zip/QuickZip.swift
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,7 @@ extension Zip {
*/
public class func quickZipFiles(_ paths: [URL], fileName: String, progress: ((_ progress: Double) -> ())?) throws -> URL {
var fileNameWithExtension = fileName
if !fileName.hasSuffix(".zip") {
fileNameWithExtension += ".zip"
}

print("fileNameWithExtension: \(fileNameWithExtension)")

if !fileName.hasSuffix(".zip") { fileNameWithExtension += ".zip" }
let destinationUrl = FileManager.default.temporaryDirectory.appendingPathComponent(fileNameWithExtension)
try self.zipFiles(paths: paths, zipFilePath: destinationUrl, progress: progress)
return destinationUrl
Expand Down
56 changes: 18 additions & 38 deletions Sources/Zip/Zip.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,21 @@ public class Zip {
progress: ((_ progress: Double) -> ())? = nil,
fileOutputHandler: ((_ unzippedFile: URL) -> Void)? = nil
) throws {
let fileManager = FileManager.default

// Check whether a zip file exists at path.
let path = zipFilePath.path
if fileManager.fileExists(atPath: path) == false || !isValidFileExtension(zipFilePath.pathExtension) {
if FileManager.default.fileExists(atPath: path) == false || !isValidFileExtension(zipFilePath.pathExtension) {
throw ZipError.fileNotFound
}

// Unzip set up
var ret: Int32 = 0
var crc_ret: Int32 = 0
let bufferSize: UInt32 = 4096
var buffer = Array<CUnsignedChar>(repeating: 0, count: Int(bufferSize))

// Progress handler set up
var totalSize: Double = 0.0
var currentPosition: Double = 0.0
let fileAttributes = try fileManager.attributesOfItem(atPath: path)
let fileAttributes = try FileManager.default.attributesOfItem(atPath: path)
if let attributeFileSize = fileAttributes[FileAttributeKey.size] as? Double {
totalSize += attributeFileSize
}
Expand All @@ -71,7 +68,6 @@ public class Zip {
let zip = unzOpen64(path)
defer { unzClose(zip) }
if unzGoToFirstFile(zip) != UNZ_OK {
print("XXXXXXXXXXXXXXXXXXXXXXXX - 1")
throw ZipError.unzipFail
}
repeat {
Expand All @@ -81,15 +77,13 @@ public class Zip {
ret = unzOpenCurrentFile(zip)
}
if ret != UNZ_OK {
print("XXXXXXXXXXXXXXXXXXXXXXXX - 2")
throw ZipError.unzipFail
}
var fileInfo = unz_file_info64()
memset(&fileInfo, 0, MemoryLayout<unz_file_info>.size)
ret = unzGetCurrentFileInfo64(zip, &fileInfo, nil, 0, nil, 0, nil, 0)
if ret != UNZ_OK {
unzCloseCurrentFile(zip)
print("XXXXXXXXXXXXXXXXXXXXXXXX - 3")
throw ZipError.unzipFail
}
currentPosition += Double(fileInfo.compressed_size)
Expand All @@ -102,7 +96,6 @@ public class Zip {

var pathString = String(cString: fileName)
guard !pathString.isEmpty else {
print("XXXXXXXXXXXXXXXXXXXXXXXX - 4")
throw ZipError.unzipFail
}

Expand All @@ -120,7 +113,6 @@ public class Zip {
// `.standardized` removes any `..` to move a level up.
// If we then check that the `fullPath` starts with the destination directory we know we are not extracting "outside" the destination.
guard fullPath.starts(with: destination.standardizedFileURL.path) else {
print("XXXXXXXXXXXXXXXXXXXXXXXX - 5")
throw ZipError.unzipFail
}

Expand All @@ -140,13 +132,13 @@ public class Zip {

do {
if isDirectory {
try fileManager.createDirectory(atPath: fullPath, withIntermediateDirectories: true, attributes: directoryAttributes)
try FileManager.default.createDirectory(atPath: fullPath, withIntermediateDirectories: true, attributes: directoryAttributes)
} else {
let parentDirectory = (fullPath as NSString).deletingLastPathComponent
try fileManager.createDirectory(atPath: parentDirectory, withIntermediateDirectories: true, attributes: directoryAttributes)
try FileManager.default.createDirectory(atPath: parentDirectory, withIntermediateDirectories: true, attributes: directoryAttributes)
}
} catch {}
if fileManager.fileExists(atPath: fullPath) && !isDirectory && !overwrite {
if FileManager.default.fileExists(atPath: fullPath) && !isDirectory && !overwrite {
unzCloseCurrentFile(zip)
ret = unzGoToNextFile(zip)
}
Expand All @@ -155,22 +147,22 @@ public class Zip {
let filePointer: UnsafeMutablePointer<FILE>? = fopen(fullPath, "wb")
while let filePointer {
let readBytes = unzReadCurrentFile(zip, &buffer, bufferSize)
print("readBytes: \(readBytes)")
guard readBytes > 0 else { break }
guard fwrite(buffer, Int(readBytes), 1, filePointer) == 1 else {
print("XXXXXXXXXXXXXXXXXXXXXXXX - 6")
throw ZipError.unzipFail
}
writeBytes += UInt64(readBytes)
}

if let filePointer { fclose(filePointer) }

crc_ret = unzCloseCurrentFile(zip)
if crc_ret == UNZ_CRCERROR {
print("XXXXXXXXXXXXXXXXXXXXXXXX - 7")
if unzCloseCurrentFile(zip) == UNZ_CRCERROR {
throw ZipError.unzipFail
}
print("writeBytes: \(writeBytes)")
print("fileInfo.uncompressed_size: \(fileInfo.uncompressed_size)")
guard writeBytes == fileInfo.uncompressed_size else {
// WINDOWS FAILS HERE
print("XXXXXXXXXXXXXXXXXXXXXXXX - 8")
throw ZipError.unzipFail
}
Expand All @@ -183,9 +175,9 @@ public class Zip {
do {
// TODO: Set permissions properly on Windows
#if os(Windows)
try fileManager.setAttributes([.posixPermissions : NSNumber(value: Int16(0o600))], ofItemAtPath: fullPath)
try FileManager.default.setAttributes([.posixPermissions : NSNumber(value: Int16(0o600))], ofItemAtPath: fullPath)
#else
try fileManager.setAttributes([.posixPermissions : permissions], ofItemAtPath: fullPath)
try FileManager.default.setAttributes([.posixPermissions : permissions], ofItemAtPath: fullPath)
#endif
} catch {
print("Failed to set permissions to file \(fullPath), error: \(error)")
Expand All @@ -207,14 +199,12 @@ public class Zip {
}

progressTracker.completedUnitCount = Int64(currentPosition)

} while (ret == UNZ_OK && ret != UNZ_END_OF_LIST_OF_FILE)

// Completed. Update progress handler.
if let progressHandler = progress {
progressHandler(1.0)
}

progressTracker.completedUnitCount = Int64(totalSize)
}

Expand All @@ -239,8 +229,6 @@ public class Zip {
compression: ZipCompression = .DefaultCompression,
progress: ((_ progress: Double) -> ())? = nil
) throws {
let fileManager = FileManager.default

let processedPaths = ZipUtilities().processZipPaths(paths)

// Zip set up
Expand All @@ -252,10 +240,8 @@ public class Zip {
// Get `totalSize` for progress handler
for path in processedPaths {
do {
let filePath = path.filePath()
let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
let fileSize = fileAttributes[FileAttributeKey.size] as? Double
if let fileSize {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: path.filePath)
if let fileSize = fileAttributes[FileAttributeKey.size] as? Double {
totalSize += fileSize
}
} catch {}
Expand All @@ -269,22 +255,18 @@ public class Zip {
// Begin Zipping
let zip = zipOpen(zipFilePath.path, APPEND_STATUS_CREATE)
for path in processedPaths {
let filePath = path.filePath()
let filePath = path.filePath
var isDirectory: ObjCBool = false
_ = fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory)
_ = FileManager.default.fileExists(atPath: filePath, isDirectory: &isDirectory)
if !isDirectory.boolValue {
guard let input = fopen(filePath, "r") else {
throw ZipError.zipFail
}
defer { fclose(input) }
let fileName = path.fileName
var zipInfo: zip_fileinfo = zip_fileinfo(
dos_date: 0,
internal_fa: 0,
external_fa: 0
)
var zipInfo: zip_fileinfo = zip_fileinfo(dos_date: 0, internal_fa: 0, external_fa: 0)
do {
let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
let fileAttributes = try FileManager.default.attributesOfItem(atPath: filePath)
if let fileDate = fileAttributes[FileAttributeKey.modificationDate] as? Date {
zipInfo.dos_date = fileDate.dosDate
}
Expand Down Expand Up @@ -324,7 +306,6 @@ public class Zip {
if let progressHandler = progress, currentPosition / totalSize != 1 {
progressHandler(currentPosition / totalSize)
}

progressTracker.completedUnitCount = Int64(currentPosition)

zipCloseFileInZip(zip)
Expand All @@ -337,7 +318,6 @@ public class Zip {
if let progressHandler = progress{
progressHandler(1.0)
}

progressTracker.completedUnitCount = Int64(totalSize)
}

Expand Down
42 changes: 17 additions & 25 deletions Sources/Zip/ZipUtilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,71 +30,63 @@ internal class ZipUtilities {
*/
let includeRootDirectory = true

// File manager
let fileManager = FileManager.default

/**
* ProcessedFilePath struct
*/
internal struct ProcessedFilePath {
let filePathURL: URL
let fileName: String?

func filePath() -> String {
return filePathURL.path
var filePath: String {
filePathURL.path
}
}

// MARK: Path processing

/**
Process zip paths
Process zip paths

- parameter paths: Paths as `URL`.
- Parameter paths: Paths as `URL`.

- returns: Array of `ProcessedFilePath` structs.
- Returns: Array of `ProcessedFilePath` structs.
*/
internal func processZipPaths(_ paths: [URL]) -> [ProcessedFilePath] {
var processedFilePaths = [ProcessedFilePath]()
for path in paths {
let filePath = path.path
for pathURL in paths {
var isDirectory: ObjCBool = false
_ = fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory)
_ = FileManager.default.fileExists(atPath: pathURL.path, isDirectory: &isDirectory)
if !isDirectory.boolValue {
let processedPath = ProcessedFilePath(filePathURL: path, fileName: path.lastPathComponent)
let processedPath = ProcessedFilePath(filePathURL: pathURL, fileName: pathURL.lastPathComponent)
processedFilePaths.append(processedPath)
} else {
let directoryContents = expandDirectoryFilePath(path)
let directoryContents = expandDirectoryFilePath(pathURL)
processedFilePaths.append(contentsOf: directoryContents)
}
}
return processedFilePaths
}

/**
Expand directory contents and parse them into ProcessedFilePath structs.
Expand directory contents and parse them into `ProcessedFilePath` structs.

- parameter directory: Path of folder as `URL`.
- Parameter directory: Path of folder as `URL`.

- returns: Array of `ProcessedFilePath` structs.
- Returns: Array of `ProcessedFilePath` structs.
*/
internal func expandDirectoryFilePath(_ directory: URL) -> [ProcessedFilePath] {
var processedFilePaths = [ProcessedFilePath]()
let directoryPath = directory.path
if let enumerator = fileManager.enumerator(atPath: directoryPath) {
if let enumerator = FileManager.default.enumerator(atPath: directory.path) {
while let filePathComponent = enumerator.nextObject() as? String {
let path = directory.appendingPathComponent(filePathComponent)
let filePath = path.path

let pathURL = directory.appendingPathComponent(filePathComponent)
var isDirectory: ObjCBool = false
_ = fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory)
_ = FileManager.default.fileExists(atPath: pathURL.path, isDirectory: &isDirectory)
if !isDirectory.boolValue {
var fileName = filePathComponent
if includeRootDirectory {
let directoryName = directory.lastPathComponent
fileName = (directoryName as NSString).appendingPathComponent(filePathComponent)
fileName = (directory.lastPathComponent as NSString).appendingPathComponent(filePathComponent)
}
let processedPath = ProcessedFilePath(filePathURL: path, fileName: fileName)
let processedPath = ProcessedFilePath(filePathURL: pathURL, fileName: fileName)
processedFilePaths.append(processedPath)
}
}
Expand Down

0 comments on commit 59ea45f

Please sign in to comment.