make find() configurable to ignore hidden files & directories

This commit is contained in:
Rob Jonson
2021-07-28 15:12:09 +01:00
parent 6e8a42f01d
commit f593437cf5
3 changed files with 36 additions and 2 deletions

View File

@@ -227,7 +227,7 @@ We provide `find()` for recursive listing:
```swift
for path in Path.home.find() {
// descends all directories, and includes hidden files
// descends all directories, and includes hidden files by default
// so it behaves the same as the terminal command `find`
}
```
@@ -235,7 +235,7 @@ for path in Path.home.find() {
It is configurable:
```swift
for path in Path.home.find().depth(max: 1).extension("swift").type(.file) {
for path in Path.home.find().depth(max: 1).extension("swift").type(.file).hidden(false) {
//
}
```

View File

@@ -31,6 +31,9 @@ public extension Path {
/// The file extensions find operations will return. Files *and* directories unless you filter for `kinds`.
private(set) public var extensions: Set<String>?
/// Whether to return hidden files
public var hidden:Bool = true
}
}
@@ -52,6 +55,10 @@ extension Path.Finder: Sequence, IteratorProtocol {
}
#endif
if !hidden, path.basename().hasPrefix(".") {
enumerator.skipDescendants()
continue
}
if let type = path.type, !types.contains(type) { continue }
if let exts = extensions, !exts.contains(path.extension) { continue }
return path
@@ -114,6 +121,12 @@ public extension Path.Finder {
extensions!.insert(ext)
return self
}
/// Whether to skip hidden files and folders.
func hidden(_ hidden: Bool) -> Path.Finder {
self.hidden = hidden
return self
}
/// The return type for `Path.Finder`
enum ControlFlow {

View File

@@ -136,6 +136,27 @@ extension PathTests {
}
}
func testFindHidden() 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 tmpdir.b.join("foo.txt").touch()
XCTAssertEqual(
Set(tmpdir.find().hidden(true)),
Set([dotFoo,tmpDotA,tmpDotAFoo,tmpB,tmpBFoo]),
relativeTo: tmpdir)
XCTAssertEqual(
Set(tmpdir.find().hidden(false)),
Set([tmpB,tmpBFoo]),
relativeTo: tmpdir)
}
}
func testFindExtension() throws {
try Path.mktemp { tmpdir in
try tmpdir.join("foo.json").touch()