Created
May 29, 2025 01:28
-
-
Save codelynx/f3c9b14881f3f634a00803b058e0df83 to your computer and use it in GitHub Desktop.
build directory tree as String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension FileManager { | |
func makeTree(atPath path: String, level: Int) throws -> [String] { | |
var strings = [String]() | |
let items = try self.contentsOfDirectory(atPath: path) | |
for item in items.sorted(by: { ($0 as NSString).lastPathComponent < ($1 as NSString).lastPathComponent }) { | |
var isDirectory: ObjCBool = false | |
let itemPath = (path as NSString).appendingPathComponent(item) | |
if self.fileExists(atPath: itemPath, isDirectory: &isDirectory) && isDirectory.boolValue { | |
strings.append("+ " + (item as NSString).lastPathComponent) | |
if level > 1 || level == 0 { | |
strings += (try self.makeTree(atPath: itemPath, level: level - 1)).map { "| " + $0 } | |
} | |
} | |
} | |
return strings.map { " \($0)" } | |
} | |
func tree(atPath path: String, level: Int) throws -> String { | |
return try self.makeTree(atPath: path, level: level).joined(separator: "\n") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment