Adding ls -a like functionality to Path.ls()

This commit is contained in:
Luciano Almeida
2019-01-20 19:23:40 -02:00
committed by Max Howell
parent 86798755be
commit d8ea357459
2 changed files with 33 additions and 6 deletions

View File

@@ -1,14 +1,18 @@
import Foundation
public extension Path {
/// same as the `ls` command is shallow
func ls() throws -> [Entry] {
let relativePaths = try FileManager.default.contentsOfDirectory(atPath: string)
func convert(relativePath: String) -> Entry {
let path = self/relativePath
/// Same as the `ls` command is shallow
/// - Parameter skipHiddenFiles: Same as the `ls -a` if false. Otherwise returns only the non hidden files. Default is false.
func ls(skipHiddenFiles: Bool = false) throws -> [Entry] {
let options: FileManager.DirectoryEnumerationOptions = skipHiddenFiles ? [.skipsHiddenFiles] : []
let paths = try FileManager.default.contentsOfDirectory(at: url,
includingPropertiesForKeys: nil,
options: options)
func convert(url: URL) -> Entry? {
guard let path = Path(url.path) else { return nil }
return Entry(kind: path.isDirectory ? .directory : .file, path: path)
}
return relativePaths.map(convert)
return paths.compactMap(convert)
}
}

View File

@@ -17,6 +17,7 @@ class PathTests: XCTestCase {
try tmpdir.join("a").mkdir().join("c").touch()
try tmpdir.join("b").touch()
try tmpdir.join("c").touch()
try tmpdir.join(".d").mkdir().join("e").touch()
var paths = Set<String>()
var dirs = 0
@@ -26,8 +27,30 @@ class PathTests: XCTestCase {
}
paths.insert(entry.path.basename())
}
XCTAssertEqual(dirs, 2)
XCTAssertEqual(paths, ["a", "b", "c", ".d"])
}
func testEnumerationSkippingHiddenFiles() throws {
let tmpdir_ = try TemporaryDirectory()
let tmpdir = tmpdir_.path
try tmpdir.join("a").mkdir().join("c").touch()
try tmpdir.join("b").touch()
try tmpdir.join("c").touch()
try tmpdir.join(".d").mkdir().join("e").touch()
var paths = Set<String>()
var dirs = 0
for entry in try tmpdir.ls(skipHiddenFiles: true) {
if entry.kind == .directory {
dirs += 1
}
paths.insert(entry.path.basename())
}
XCTAssertEqual(dirs, 1)
XCTAssertEqual(paths, ["a", "b", "c"])
}
func testRelativeTo() {