I'm writing to save data on multiple platforms. I uses https://github.com/apple/swift-tools-support-core and extend the fileSystem there to set some extra attributes for IOS. I also would like to set it for macOS but there seams to be a problem in my understanding of the FileProtectionType.complete. This type is available on both macOS and iOS. But on macOS when I try it results in an error.
Is the FileProtectionType.complete not available in a macOS sandbox app?
my code is.
import TSCBasic
import Foundation
var filesystem: FileSystem = localFileSystem
extension FileSystem {
/// Attemps to set the `FileProtectionType.complete` when on Apple platforms, otherwise it just writes the bytes
/// - Parameter file: the file to change the protection type off
/// - Throws: `NSError` occuring when changing file attributes.
func writeWithCompleteProtectionOniOS(file: AbsolutePath, content: String) throws {
guard let data = content.data(using: .utf8) else {
throw AgreesError.invalidUTF8(atFunction: #function, inFile: #filePath)
}
do {
// although the file protectionKey is available on macOS it has no effect apparently and results in an error.
#if os(iOS)
FileManager.default.createFile(
atPath: file.pathString,
contents: data,
attributes: [FileAttributeKey.protectionKey : FileProtectionType.complete]
)
try FileManager.default.setAttributes([.protectionKey: FileProtectionType.complete], ofItemAtPath: file.pathString)
#else
logger.log(
level: .warning,
message: "On non apple platforms files should be protected otherwise.",
metadata: ["file": .string(file.prettyPath())],
source: String(reflecting: FileSystem.self), file: #filePath, function: #function, line: #line
)
try filesystem.writeFileContents(file, bytes: .init(encodingAsUTF8: content), atomically: true)
#endif
} catch {
throw AgreesError.writeTo(file: file, error, atFunction: #function, inFile: #filePath)
}
}
}