Files
HtmlRW/Sources/BindingGenerator/Extensions/Url+Ext.swift

69 lines
1.9 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// Url+Ext.swift
// gen_html
//
// Created by Isaac Paul on 9/25/25.
//
import Foundation
extension URL {
enum FileType {
case directory
case regularFile
case other
}
func fetchFileType() throws -> FileType {
let values = try self.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey])
if values.isDirectory == true {
return .directory
}
if values.isRegularFile == true {
return .regularFile
}
if self.hasDirectoryPath {
return .directory
}
return .other
}
func getRelativePathComponents(
to toFolder: URL, // URL A
) throws -> [String] {
// 1) Get path components of As directory
let aDirComponents = toFolder.pathComponents
// 2) Get path components of B
let bComponents = self.pathComponents
// Ensure B is actually a prefix of As directory
guard bComponents.count <= aDirComponents.count,
aDirComponents[0..<bComponents.count] == bComponents[0..<bComponents.count]
else {
// B is not a parent of As directory; just return destFolder
throw AppError("Url \(self.absoluteString) is not a relative path to \(toFolder.absoluteString)")
}
// 3) Compute the relative components from B to As directory
let relativeComponents = Array(aDirComponents[bComponents.count...])
return relativeComponents
}
func appendRelativePath(
from fromFolder: URL, // URL A
base baseFolder: URL // URL B
) throws -> URL {
let relativeComponents = try baseFolder.getRelativePathComponents(to: fromFolder)
// 4) Append them one by one onto C
var result = self
for comp in relativeComponents {
result.appendPathComponent(comp)
}
return result
}
}