2021-12-01 22:47:19 +01:00
|
|
|
//
|
|
|
|
// File.swift
|
|
|
|
//
|
|
|
|
//
|
|
|
|
// Created by iMac on 01.12.21.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
|
2021-12-21 15:50:49 +01:00
|
|
|
protocol DiskWriter: AnyObject {
|
2021-12-01 22:47:19 +01:00
|
|
|
|
2021-12-21 15:50:49 +01:00
|
|
|
var storageFile: FileHandle { get set }
|
2021-12-01 22:47:19 +01:00
|
|
|
|
|
|
|
var storageFileUrl: URL { get }
|
|
|
|
}
|
|
|
|
|
|
|
|
extension DiskWriter {
|
2021-12-21 15:50:49 +01:00
|
|
|
|
|
|
|
func replaceFile(data: String) throws {
|
|
|
|
let data = data.data(using: .utf8)!
|
|
|
|
try storageFile.close()
|
|
|
|
try data.write(to: storageFileUrl)
|
|
|
|
storageFile = try FileHandle(forUpdating: storageFileUrl)
|
|
|
|
if #available(macOS 10.15.4, *) {
|
|
|
|
try storageFile.seekToEnd()
|
|
|
|
} else {
|
|
|
|
storageFile.seekToEndOfFile()
|
|
|
|
}
|
|
|
|
}
|
2021-12-01 22:47:19 +01:00
|
|
|
|
|
|
|
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 != "" }
|
|
|
|
}
|
|
|
|
}
|