Schafkopf-Server/Sources/App/Management/DiskWriter.swift

67 lines
1.7 KiB
Swift
Raw Normal View History

2021-12-01 22:47:19 +01:00
//
// 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
}
}
2021-12-03 18:03:29 +01:00
func readDataFromDisk() throws -> Data {
2021-12-01 22:47:19 +01:00
if #available(macOS 10.15.4, *) {
guard let data = try storageFile.readToEnd() else {
try storageFile.seekToEnd()
2021-12-03 18:03:29 +01:00
return Data()
2021-12-01 22:47:19 +01:00
}
2021-12-03 18:03:29 +01:00
return data
2021-12-01 22:47:19 +01:00
} else {
2021-12-03 18:03:29 +01:00
return storageFile.readDataToEndOfFile()
2021-12-01 22:47:19 +01:00
}
}
2021-12-03 18:03:29 +01:00
func readLinesFromDisk() throws -> [String] {
let data = try readDataFromDisk()
return parseLines(data: data)
}
2021-12-01 22:47:19 +01:00
private func parseLines(data: Data) -> [String] {
String(data: data, encoding: .utf8)!
.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { $0 != "" }
}
}