-
-
Save mfwgenerics/d1ec89eb80c95da9d542a03b49b5e15b to your computer and use it in GitHub Desktop.
This file contains 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
import java.nio.file.Path | |
import kotlin.io.path.* | |
class PrefixPair( | |
val indent: String = "", | |
val before: String = "", | |
) | |
class Prefix( | |
val pre: PrefixPair = PrefixPair(), | |
val post: PrefixPair = PrefixPair(), | |
) | |
val NO_PREFIX = Prefix( | |
PrefixPair("", ""), | |
PrefixPair("", "") | |
) | |
val PIPES_PREFIX = Prefix( | |
PrefixPair("│ ", "├── "), | |
PrefixPair(" ", "└── ") | |
) | |
fun drawFileTree( | |
prefix: Prefix, | |
dir: Path, | |
margin: String, | |
out: StringBuilder | |
) { | |
val entries = dir.listDirectoryEntries() | |
entries.forEachIndexed { ix, entry -> | |
val p = if (ix < entries.size - 1) prefix.pre else prefix.post | |
out.append("$margin${p.before}${entry.name}") | |
if (entry.isDirectory()) { | |
out.append("/\n") | |
drawFileTree(PIPES_PREFIX, entry, "$margin${p.indent}", out) | |
} else { | |
out.append("\n") | |
} | |
} | |
} | |
fun drawFileTree(output: Path): String = | |
"${StringBuilder().also { drawFileTree(NO_PREFIX, output, "", it) }}" | |
fun main() { | |
println(drawFileTree( | |
Path(".") | |
)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment