blob: 4ba850d37fb0f2a7dada688c428c0b3409290268 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
package org.jetbrains.dokka.dokkatoo.utils
import java.io.File
import java.nio.file.Path
// based on https://gist.github.com/mfwgenerics/d1ec89eb80c95da9d542a03b49b5e15b
// context: https://kotlinlang.slack.com/archives/C0B8MA7FA/p1676106647658099
fun Path.toTreeString(): String = toFile().toTreeString()
fun File.toTreeString(): String = when {
isDirectory -> name + "/\n" + buildTreeString(this)
else -> name
}
private fun buildTreeString(
dir: File,
margin: String = "",
): String {
val entries = dir.listDirectoryEntries()
return entries.joinToString("\n") { entry ->
val (currentPrefix, nextPrefix) = when (entry) {
entries.last() -> PrefixPair.LAST_ENTRY
else -> PrefixPair.INTERMEDIATE
}
buildString {
append("$margin${currentPrefix}${entry.name}")
if (entry.isDirectory) {
append("/")
if (entry.countDirectoryEntries() > 0) {
append("\n")
}
append(buildTreeString(entry, margin + nextPrefix))
}
}
}
}
private fun File.listDirectoryEntries(): Sequence<File> =
walkTopDown().maxDepth(1).filter { it != this@listDirectoryEntries }
private fun File.countDirectoryEntries(): Int =
listDirectoryEntries().count()
private data class PrefixPair(
/** The current entry should be prefixed with this */
val currentPrefix: String,
/** If the next item is a directory, it should be prefixed with this */
val nextPrefix: String,
) {
companion object {
/** Prefix pair for a non-last directory entry */
val INTERMEDIATE = PrefixPair("├── ", "│ ")
/** Prefix pair for the last directory entry */
val LAST_ENTRY = PrefixPair("└── ", " ")
}
}
|