LMConsolidator // Optimize fixEOF().

This commit is contained in:
ShikiSuen 2023-09-03 14:31:22 +08:00
parent 145fa34ebd
commit 80f9b9bb46
1 changed files with 23 additions and 27 deletions

View File

@ -46,34 +46,30 @@ public extension vChewingLM {
/// - Parameter path:
/// - Returns:
@discardableResult public static func fixEOF(path: String) -> Bool {
let urlPath = URL(fileURLWithPath: path)
if FileManager.default.fileExists(atPath: path) {
var strIncoming = ""
do {
strIncoming += try String(contentsOf: urlPath, encoding: .utf8)
/// Swift LMConsolidator EOF
/// consolidate()
if !strIncoming.hasSuffix("\n") {
vCLog("EOF Fix Necessity Confirmed, Start Fixing.")
if let writeFile = FileHandle(forUpdatingAtPath: path),
let endl = "\n".data(using: .utf8)
{
writeFile.seekToEndOfFile()
writeFile.write(endl)
writeFile.closeFile()
} else {
return false
}
}
} catch {
vCLog("EOF Fix Failed w/ File: \(path)")
vCLog("EOF Fix Failed w/ Error: \(error).")
return false
}
vCLog("EOF Successfully Ensured (with possible autofixes performed).")
return true
var fileSize: UInt64?
do {
let dict = try FileManager.default.attributesOfItem(atPath: path)
if let value = dict[FileAttributeKey.size] as? UInt64 { fileSize = value }
} catch {
vCLog("EOF Fix Failed: File Missing at \(path).")
return false
}
guard let fileSize = fileSize else { return false }
guard let writeFile = FileHandle(forUpdatingAtPath: path) else {
vCLog("EOF Fix Failed: File Not Writable at \(path).")
return false
}
defer { writeFile.closeFile() }
/// Swift LMConsolidator EOF
/// consolidate()
writeFile.seek(toFileOffset: fileSize - 1)
if writeFile.readDataToEndOfFile().first != 0x0A {
vCLog("EOF Missing Confirmed, Start Fixing.")
var newData = Data()
newData.append(0x0A)
writeFile.write(newData)
vCLog("EOF Successfully Assured.")
}
vCLog("EOF Fix Failed: File Missing at \(path).")
return false
}