Add .isAncestor(of:) method to URL

This commit is contained in:
1024jp 2024-05-13 07:16:52 +09:00
parent 0033a80c31
commit 9cf39fe4a0
2 changed files with 25 additions and 0 deletions

View File

@ -72,6 +72,20 @@ extension URL {
self.components(relativeTo: baseURL).joined(separator: "/")
}
/// Checks the given URL is ancestor of the receiver.
///
/// - Parameter url: The child candidate URL.
/// - Returns: `true` if the given URL is child.
func isAncestor(of url: URL) -> Bool {
let ancestorComponents = self.standardizedFileURL.resolvingSymlinksInPath().pathComponents
let childComponents = url.standardizedFileURL.resolvingSymlinksInPath().pathComponents
return ancestorComponents.count < childComponents.count
&& !zip(ancestorComponents, childComponents).contains(where: !=)
}
}

View File

@ -71,6 +71,17 @@ struct URLExtensionsTests {
}
@Test func ancestor() throws {
let leaf = URL(fileURLWithPath: "/Dog/Cow/Cat")
let parent = leaf.deletingLastPathComponent()
#expect(parent.isAncestor(of: leaf))
#expect(!parent.isAncestor(of: URL(fileURLWithPath: "/Dog/Cow 1/Cat")))
#expect(!leaf.isAncestor(of: leaf))
}
@Test func createItemReplacementDirectory() throws {
#expect(throws: Never.self) { try URL.itemReplacementDirectory }