All checks were successful
Test Workflow / Lint and test library (push) Successful in 17m4s
> Search for specific commit by hash or metadata and print its content. To satisfy this final requirement, we need to have `toString()` implemented for version manager `Object`s which will allow them to be easily (and nicely) printed if needed (includes tests). Reviewed-on: #4
36 lines
1.1 KiB
Kotlin
36 lines
1.1 KiB
Kotlin
package tinyvm
|
|
|
|
/**
|
|
* Tree nodes are either trees or blobs, represented by this sealed class.
|
|
*/
|
|
sealed class Node(type: String) : Object(type)
|
|
|
|
/**
|
|
* A tree is a set of named nodes.
|
|
*/
|
|
class Tree(val nodes: Map<String, Node>) : Node("tree") {
|
|
// For simplicity just use the hex-formatted hash, not the actual value like git does.
|
|
override val data: String
|
|
get() =
|
|
nodes.map { (name, node) ->
|
|
"${node.type} $name\u0000${node.hash()}"
|
|
}.sorted().joinToString()
|
|
|
|
override fun toString(): String =
|
|
"tree ${hash()}\n" +
|
|
nodes.map { (name, node) ->
|
|
when (node) {
|
|
is Tree -> "+$name/\n"
|
|
is Blob -> "+$name\n"
|
|
} + node.toString().leftMargin()
|
|
}.sorted().joinToString("\n")
|
|
}
|
|
|
|
/**
|
|
* A blob is a data container.
|
|
*/
|
|
class Blob(override val data: String) : Node("blob") {
|
|
override fun toString(): String = "blob ${hash()}\n${data.leftMargin()}"
|
|
}
|
|
|
|
private fun String.leftMargin(): String = split('\n').joinToString("\n") { "| $it" } |