luhahaha
luhahaha

Reputation: 125

Extract directory entry from archive

Is it possible to extract a directory entry from an archive? How can I do it?

Code to extract a file.txt from the archive:

let fileManager = FileManager()
    let currentWorkingPath = fileManager.currentDirectoryPath
    var archiveURL = URL(fileURLWithPath: currentWorkingPath)
    archiveURL.appendPathComponent("archive.zip")
    guard let archive = Archive(url: archiveURL, accessMode: .read) else  {
        return
    }
    guard let entry = archive["file.txt"] else {
        return
    }
    var destinationURL = URL(fileURLWithPath: currentWorkingPath)
    destinationURL.appendPathComponent("out.txt")
    do {
        try archive.extract(entry, to: destinationURL)
    } catch {
        print("Extracting entry from archive failed with error:\(error)")
    }

If as entry I use a subdirectory path of the zip file, can I extract that directory and all its contents?

Upvotes: 1

Views: 918

Answers (1)

Thomas Zoechling
Thomas Zoechling

Reputation: 34253

ZIP archives don't store parent/child relationships for entries. An archive is a flat list of entries, that have a path property.
Because archives are organized as a list - and not as a tree - there is no efficient way to obtain a subtree.

In ZIP Foundation, Archive conforms to Sequence. So you can use filter to find all entries with a specific path prefix. e.g.

let entries = archive.filter { $0.path.starts(with: "Test/") }

You can then iterate over all qualifying entries and use the extract code from your question.
There are some edge cases to consider though:

  • You will have to create (intermediate) directories yourself (e.g. with FileManager.createDirectory(...) during extraction.
  • ZIP archives don't require dedicated .directory entries. The best approach is, to create the directory hierarchy "on-demand". (E.g. if you encounter an entry with a parent path that doesn't exist yet, you create it)
  • There is no guaranteed order of entries. So you can't make any assumptions on already existing paths during extraction.

Upvotes: 4

Related Questions