Schafkopf-Server/Sources/App/Management/DiskWriter.swift
2021-12-01 22:47:19 +01:00

63 lines
1.6 KiB
Swift

//
// File.swift
//
//
// Created by iMac on 01.12.21.
//
import Foundation
protocol DiskWriter {
var storageFile: FileHandle { get }
var storageFileUrl: URL { get }
}
extension DiskWriter {
static func prepareFile(at url: URL) throws -> FileHandle {
if !FileManager.default.fileExists(atPath: url.path) {
try Data().write(to: url)
}
return try FileHandle(forUpdating: url)
}
func writeToDisk(line: String) -> Bool {
let data = (line + "\n").data(using: .utf8)!
do {
if #available(macOS 10.15.4, *) {
try storageFile.write(contentsOf: data)
} else {
storageFile.write(data)
}
try storageFile.synchronize()
return true
} catch {
print("Failed to save data to file: \(storageFileUrl.path): \(error)")
return false
}
}
func readLinesFromDisk() throws -> [String] {
if #available(macOS 10.15.4, *) {
guard let data = try storageFile.readToEnd() else {
try storageFile.seekToEnd()
return []
}
return parseLines(data: data)
} else {
let data = storageFile.readDataToEndOfFile()
return parseLines(data: data)
}
}
private func parseLines(data: Data) -> [String] {
String(data: data, encoding: .utf8)!
.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { $0 != "" }
}
}