ref: URL utils class

This commit is contained in:
relikd
2025-11-05 03:44:49 +01:00
parent 33cec015ab
commit fb8fa41dd0
4 changed files with 52 additions and 23 deletions

View File

@@ -1,27 +1,12 @@
import Foundation
extension PreviewGenerator {
/// Calculate file / folder size.
private func getFileSize(_ path: String) -> Int64 {
var isDir: ObjCBool = false
FileManager.default.fileExists(atPath: path, isDirectory: &isDir)
if !isDir.boolValue {
return try! FileManager.default.attributesOfItem(atPath: path)[.size] as! Int64
}
var fileSize: Int64 = 0
for child in try! FileManager.default.subpathsOfDirectory(atPath: path) {
fileSize += try! FileManager.default.attributesOfItem(atPath: path + "/" + child)[.size] as! Int64
}
return fileSize
}
/// Process meta information about the file itself. Like file size and last modification.
mutating func procFileInfo(_ url: URL) {
let attrs = try? FileManager.default.attributesOfItem(atPath: url.path)
self.apply([
"FileName": escapeXML(url.lastPathComponent),
"FileSize": ByteCountFormatter.string(fromByteCount: getFileSize(url.path), countStyle: .file),
"FileModified": (attrs?[.modificationDate] as? Date)?.mediumFormat() ?? "",
"FileSize": url.fileSizeHuman(),
"FileModified": url.modificationDate()?.mediumFormat() ?? "",
])
}
}
@@ -36,3 +21,32 @@ private func escapeXML(_ stringToEscape: String) -> String {
.replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;")
}
extension URL {
/// Last modification date of file (or folder)
@inlinable func modificationDate() -> Date? {
(try? FileManager.default.attributesOfItem(atPath: self.path))?[.modificationDate] as? Date
}
/// Calls `fileSize()`. Will convert `Int` to human readable `String`.
func fileSizeHuman() -> String {
ByteCountFormatter.string(fromByteCount: self.fileSize(), countStyle: .file)
}
// MARK: - private methods
/// Calculate file or folder size.
private func fileSize() -> Int64 {
var isDir: ObjCBool = false
FileManager.default.fileExists(atPath: self.path, isDirectory: &isDir)
if !isDir.boolValue {
return try! FileManager.default.attributesOfItem(atPath: self.path)[.size] as! Int64
}
var fileSize: Int64 = 0
for child in try! FileManager.default.subpathsOfDirectory(atPath: self.path) {
fileSize += try! FileManager.default.attributesOfItem(atPath: self.path + "/" + child)[.size] as! Int64
}
return fileSize
}
}

12
src/URL+File.swift Normal file
View File

@@ -0,0 +1,12 @@
import Foundation
extension URL {
/// Folder where user can mofifications to html template
static let UserModDir: URL? =
FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
/// Returns `true` if file or folder exists.
@inlinable func exists() -> Bool {
FileManager.default.fileExists(atPath: self.path)
}
}