Files
container/Sources/ContainerClient/Archiver.swift
T
Kathryn Baldauf 8e9670c8f8 Initial commit
Co-authored-by: Aditya Ramani <a_ramani@apple.com>
Co-authored-by: Agam Dua <agam_dua@apple.com>
Co-authored-by: Danny Canter <danny_canter@apple.com>
Co-authored-by: Dmitry Kovba <dkovba@apple.com>
Co-authored-by: Eric Ernst <eric_ernst@apple.com>
Co-authored-by: Evan Hazlett <ehazlett@apple.com>
Co-authored-by: Gilbert Song <gilbertsong@apple.com>
Co-authored-by: Hugh Bussell <hbussell@apple.com>
Co-authored-by: John Logan <john_logan@apple.com>
Co-authored-by: Kathryn Baldauf <k_baldauf@apple.com>
Co-authored-by: Madhu Venugopal <mvenugopal@apple.com>
Co-authored-by: Michael Crosby <michael_crosby@apple.com>
Co-authored-by: Sidhartha Mani <sidhartha_mani@apple.com>
Co-authored-by: Tanweer Noor <tnoor@apple.com>
Co-authored-by: Ximena Perez Diaz <xperez528@gmail.com>
Co-authored-by: Yibo Zhuang <yzhuang@apple.com>
2025-06-05 15:51:55 -07:00

294 lines
10 KiB
Swift

//===----------------------------------------------------------------------===//
// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//
import ContainerizationArchive
import ContainerizationOS
import Foundation
public final class Archiver: Sendable {
public struct ArchiveEntryInfo: Sendable {
let pathOnHost: URL
let pathInArchive: URL
public init(pathOnHost: URL, pathInArchive: URL) {
self.pathOnHost = pathOnHost
self.pathInArchive = pathInArchive
}
}
public static func compress(
source: URL,
destination: URL,
followSymlinks: Bool = false,
writerConfiguration: ArchiveWriterConfiguration = ArchiveWriterConfiguration(format: .paxRestricted, filter: .gzip),
closure: (URL) -> ArchiveEntryInfo?
) throws {
let source = source.standardizedFileURL
let destination = destination.standardizedFileURL
let fileManager = FileManager.default
try? fileManager.removeItem(at: destination)
do {
let directory = destination.deletingLastPathComponent()
try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
guard
let enumerator = FileManager.default.enumerator(
at: source,
includingPropertiesForKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]
)
else {
throw Error.fileDoesNotExist(source)
}
var entryInfo = [ArchiveEntryInfo]()
if !source.isDirectory {
if let info = closure(source) {
entryInfo.append(info)
}
} else {
while let url = enumerator.nextObject() as? URL {
guard let info = closure(url) else {
continue
}
entryInfo.append(info)
}
}
let archiver = try ArchiveWriter(
configuration: writerConfiguration
)
try archiver.open(file: destination)
for info in entryInfo {
guard let entry = try Self._createEntry(entryInfo: info) else {
throw Error.failedToCreateEntry
}
try Self._compressFile(item: info.pathOnHost, entry: entry, archiver: archiver)
}
try archiver.finishEncoding()
} catch {
try? fileManager.removeItem(at: destination)
throw error
}
}
public static func uncompress(source: URL, destination: URL) throws {
let source = source.standardizedFileURL
let destination = destination.standardizedFileURL
// TODO: ArchiveReader needs some enhancement to support buffered uncompression
let reader = try ArchiveReader(
format: .paxRestricted,
filter: .gzip,
file: source
)
for (entry, data) in reader {
guard let path = entry.path else {
continue
}
let uncompressPath = destination.appendingPathComponent(path)
let fileManager = FileManager.default
switch entry.fileType {
case .blockSpecial, .characterSpecial, .socket:
continue
case .directory:
try fileManager.createDirectory(
at: uncompressPath,
withIntermediateDirectories: true,
attributes: [
FileAttributeKey.posixPermissions: entry.permissions
]
)
case .regular:
try fileManager.createDirectory(
at: uncompressPath.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: [
FileAttributeKey.posixPermissions: 0o755
]
)
let success = fileManager.createFile(
atPath: uncompressPath.path,
contents: data,
attributes: [
FileAttributeKey.posixPermissions: entry.permissions
]
)
if !success {
throw POSIXError.fromErrno()
}
try data.write(to: uncompressPath)
case .symbolicLink:
guard let target = entry.symlinkTarget else {
continue
}
try fileManager.createDirectory(
at: uncompressPath.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: [
FileAttributeKey.posixPermissions: 0o755
]
)
try fileManager.createSymbolicLink(atPath: uncompressPath.path, withDestinationPath: target)
continue
default:
continue
}
// FIXME: uid/gid for compress.
try fileManager.setAttributes(
[.posixPermissions: NSNumber(value: entry.permissions)],
ofItemAtPath: uncompressPath.path
)
if let creationDate = entry.creationDate {
try fileManager.setAttributes(
[.creationDate: creationDate],
ofItemAtPath: uncompressPath.path
)
}
if let modificationDate = entry.modificationDate {
try fileManager.setAttributes(
[.modificationDate: modificationDate],
ofItemAtPath: uncompressPath.path
)
}
}
}
// MARK: private functions
private static func _compressFile(item: URL, entry: WriteEntry, archiver: ArchiveWriter) throws {
guard let stream = InputStream(url: item) else {
return
}
let writer = archiver.makeTransactionWriter()
let bufferSize = Int(1.mib())
let readBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
stream.open()
try writer.writeHeader(entry: entry)
while true {
let byteRead = stream.read(readBuffer, maxLength: bufferSize)
if byteRead <= 0 {
break
} else {
let data = Data(bytes: readBuffer, count: byteRead)
try data.withUnsafeBytes { pointer in
try writer.writeChunk(data: pointer)
}
}
}
stream.close()
try writer.finish()
}
private static func _createEntry(entryInfo: ArchiveEntryInfo, pathPrefix: String = "") throws -> WriteEntry? {
let entry = WriteEntry()
let fileManager = FileManager.default
let attributes = try fileManager.attributesOfItem(atPath: entryInfo.pathOnHost.path)
if let fileType = attributes[.type] as? FileAttributeType {
switch fileType {
case .typeBlockSpecial, .typeCharacterSpecial, .typeSocket:
return nil
case .typeDirectory:
entry.fileType = .directory
case .typeRegular:
entry.fileType = .regular
case .typeSymbolicLink:
entry.fileType = .symbolicLink
let symlinkTarget = try fileManager.destinationOfSymbolicLink(atPath: entryInfo.pathOnHost.path)
entry.symlinkTarget = symlinkTarget
default:
return nil
}
}
if let posixPermissions = attributes[.posixPermissions] as? NSNumber {
#if os(macOS)
entry.permissions = posixPermissions.uint16Value
#else
entry.permissions = posixPermissions.uint32Value
#endif
}
if let fileSize = attributes[.size] as? UInt64 {
entry.size = Int64(fileSize)
}
if let uid = attributes[.ownerAccountID] as? NSNumber {
entry.owner = uid.uint32Value
}
if let gid = attributes[.groupOwnerAccountID] as? NSNumber {
entry.group = gid.uint32Value
}
if let creationDate = attributes[.creationDate] as? Date {
entry.creationDate = creationDate
}
if let modificationDate = attributes[.modificationDate] as? Date {
entry.modificationDate = modificationDate
}
let pathTrimmed = Self._trimPathPrefix(entryInfo.pathInArchive.relativePath, pathPrefix: pathPrefix)
entry.path = pathTrimmed
return entry
}
private static func _trimPathPrefix(_ path: String, pathPrefix: String) -> String {
guard !path.isEmpty && !pathPrefix.isEmpty else {
return path
}
let decodedPath = path.removingPercentEncoding ?? path
guard decodedPath.hasPrefix(pathPrefix) else {
return decodedPath
}
let trimmedPath = String(decodedPath.suffix(from: pathPrefix.endIndex))
return trimmedPath
}
private static func _isSymbolicLink(_ path: URL) throws -> Bool {
let resourceValues = try path.resourceValues(forKeys: [.isSymbolicLinkKey])
if let isSymbolicLink = resourceValues.isSymbolicLink {
if isSymbolicLink {
return true
}
}
return false
}
}
extension Archiver {
public enum Error: Swift.Error, CustomStringConvertible {
case failedToCreateEntry
case fileDoesNotExist(_ url: URL)
public var description: String {
switch self {
case .failedToCreateEntry:
return "failed to create entry"
case .fileDoesNotExist(let url):
return "file \(url.path) does not exist"
}
}
}
}