2022-08-26 17:40:51 +02:00
|
|
|
import Foundation
|
|
|
|
|
|
|
|
extension URL {
|
|
|
|
|
|
|
|
func ensureParentFolderExistence() throws {
|
|
|
|
try deletingLastPathComponent().ensureFolderExistence()
|
|
|
|
}
|
|
|
|
|
|
|
|
func ensureFolderExistence() throws {
|
|
|
|
guard !exists else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
try FileManager.default.createDirectory(at: self, withIntermediateDirectories: true)
|
|
|
|
}
|
|
|
|
|
|
|
|
var isDirectory: Bool {
|
2022-09-05 15:56:05 +02:00
|
|
|
do {
|
|
|
|
let resources = try resourceValues(forKeys: [.isDirectoryKey])
|
|
|
|
guard let isDirectory = resources.isDirectory else {
|
|
|
|
print("No isDirectory info for \(path)")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return isDirectory
|
|
|
|
} catch {
|
|
|
|
print("Failed to get directory information from \(path): \(error)")
|
|
|
|
return false
|
|
|
|
}
|
2022-08-26 17:40:51 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var exists: Bool {
|
|
|
|
FileManager.default.fileExists(atPath: path)
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Delete the file at the url.
|
|
|
|
*/
|
|
|
|
func delete() throws {
|
|
|
|
try FileManager.default.removeItem(at: self)
|
|
|
|
}
|
|
|
|
|
|
|
|
func copy(to url: URL) throws {
|
|
|
|
if url.exists {
|
|
|
|
try url.delete()
|
|
|
|
}
|
|
|
|
try url.ensureParentFolderExistence()
|
|
|
|
try FileManager.default.copyItem(at: self, to: url)
|
|
|
|
}
|
2022-08-31 08:46:23 +02:00
|
|
|
|
|
|
|
var size: Int? {
|
|
|
|
let attributes = try? FileManager.default.attributesOfItem(atPath: path)
|
|
|
|
return (attributes?[.size] as? NSNumber)?.intValue
|
|
|
|
}
|
2022-12-09 12:09:57 +01:00
|
|
|
|
|
|
|
func resolvingFolderTraversal() -> URL? {
|
|
|
|
var components = [String]()
|
|
|
|
absoluteString.components(separatedBy: "/").forEach { part in
|
|
|
|
if part == ".." {
|
|
|
|
if !components.isEmpty {
|
2022-12-10 22:40:35 +01:00
|
|
|
_ = components.popLast()
|
2022-12-09 12:09:57 +01:00
|
|
|
} else {
|
|
|
|
components.append("..")
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if part == "." {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
components.append(part)
|
|
|
|
}
|
|
|
|
return URL(string: components.joined(separator: "/"))
|
|
|
|
}
|
2022-08-26 17:40:51 +02:00
|
|
|
}
|