Skip to content

Instantly share code, notes, and snippets.

@codelynx
Created May 29, 2025 01:28
Show Gist options
  • Save codelynx/f3c9b14881f3f634a00803b058e0df83 to your computer and use it in GitHub Desktop.
Save codelynx/f3c9b14881f3f634a00803b058e0df83 to your computer and use it in GitHub Desktop.
build directory tree as String
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