Adding ls -a like functionality to Path.ls()
This commit is contained in:
committed by
Max Howell
parent
86798755be
commit
d8ea357459
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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() {
|
||||
|
||||
Reference in New Issue
Block a user