Skip to content

Commit

Permalink
Add .isAncestor(of:) method to URL
Browse files Browse the repository at this point in the history
  • Loading branch information
1024jp committed Jun 29, 2024
1 parent 0033a80 commit 9cf39fe
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
14 changes: 14 additions & 0 deletions CotEditor/Sources/URL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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: !=)
}
}


Expand Down
11 changes: 11 additions & 0 deletions Tests/URLExtensionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down

0 comments on commit 9cf39fe

Please sign in to comment.