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