Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions Sources/Path+ls.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ public extension Path {
class Finder {
fileprivate init(path: Path) {
self.path = path
self.enumerator = FileManager.default.enumerator(atPath: path.string)
self.enumerator = FileManager.default.enumerator(at: path.url, includingPropertiesForKeys: [.isDirectoryKey])
}

/// The `path` find operations operate on.
Expand Down Expand Up @@ -42,8 +42,8 @@ extension Path.Finder: Sequence, IteratorProtocol {
guard let enumerator = enumerator else {
return nil
}
while let relativePath = enumerator.nextObject() as? String {
let path = self.path/relativePath
while let url = enumerator.nextObject() as? URL {
guard let path = Path(url: url) else { continue }

#if !os(Linux) || swift(>=5.0)
if enumerator.level > depth.upperBound {
Expand All @@ -55,7 +55,9 @@ extension Path.Finder: Sequence, IteratorProtocol {
}

if !hidden, path.basename().hasPrefix(".") {
enumerator.skipDescendants()
if url.isDirectory {
enumerator.skipDescendants()
}
continue
}
#endif
Expand Down Expand Up @@ -250,3 +252,17 @@ public enum ListDirectoryOptions {
/// Disables sorting for better performance
case unsorted
}

private extension URL {
var isDirectory: Bool {
#if swift(>=5.0) && !swift(>=5.1)
// fails for Swift 5.0 *only* (works in 4.2 :D)
// possibly only applies to Linux, but there’s no way to verify macOS anymore
var isDir: ObjCBool = false
FileManager.default.fileExists(atPath: path, isDirectory: &isDir)
return isDir.boolValue
#else
return (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
#endif
}
}
25 changes: 25 additions & 0 deletions Tests/PathTests/PathTests+ls().swift
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,31 @@ extension PathTests {
#endif
}
}

func testFindHiddenFileAlongsideDirectory() throws {
try Path.mktemp { tmpdir in
let dotFoo = try tmpdir.join(".foo.txt").touch()
let tmpDotA = try tmpdir.join(".a").mkdir()
let tmpDotAFoo = try tmpdir.join(".a").join("foo.txt").touch()
let tmpB = try tmpdir.b.mkdir()
let tmpBFoo = try tmpB.join("foo.txt").touch()
let dotBar = try tmpB.join(".bar.txt").touch()
let tmpC = try tmpdir.b.c.mkdir()
let bar = try tmpC.join("bar.txt").touch()

XCTAssertEqual(
Set(tmpdir.find().hidden(true)),
Set([dotFoo,tmpDotA,tmpDotAFoo,tmpB,tmpBFoo,tmpC,dotBar,bar]),
relativeTo: tmpdir)

#if !os(Linux) || swift(>=5)
XCTAssertEqual(
Set(tmpdir.find().hidden(false)),
Set([tmpB,tmpBFoo,tmpC,bar]),
relativeTo: tmpdir)
#endif
}
}

func testFindExtension() throws {
try Path.mktemp { tmpdir in
Expand Down
Loading