Implement toString() for objects
Test Workflow / Lint and test library (pull_request) Successful in 7m43s Details

This commit is contained in:
Gleb Koval 2023-12-02 02:36:11 +00:00
parent 14950b2f5f
commit 13ae026637
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
2 changed files with 57 additions and 9 deletions

View File

@ -15,9 +15,22 @@ class Tree(val nodes: Map<String, Node>) : Node("tree") {
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")
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" }

View File

@ -18,22 +18,22 @@ internal class RepositoryTest {
tree =
Tree(
mapOf(
"dir2" to
Tree(
mapOf(
"test1.txt" to Blob("This is a second file"),
),
),
"dir1" to
Tree(
mapOf(
"test1.txt" to Blob("Hello World!"),
),
),
"dir2" to
Tree(
mapOf(
"test2.txt" to Blob("This is a second file"),
),
),
),
),
author = Author("Gleb Koval", "gleb@koval.net"),
message = "Move test1.txt and add dir2/test2.txt",
message = "Move test1.txt to dir1 and add dir2/test1.txt",
timestamp = Instant.ofEpochSecond(50),
),
Commit(
@ -49,7 +49,7 @@ internal class RepositoryTest {
"dir2" to
Tree(
mapOf(
"test2.txt" to Blob("This is a second file"),
"test1.txt" to Blob("This is a second file"),
),
),
"README.md" to Blob("# This is a test repo!"),
@ -117,4 +117,39 @@ internal class RepositoryTest {
assertEquals(committed, repository.findCommit { it.message.matches("Move.*".toRegex()) })
assertEquals(null, repository.getCommit("00000000000000000000"))
}
@Test
fun `can display commit`() {
assertEquals(
"""
commit 804c6f0c66da0ea0eab8ac29f23a627e03a962b2
tree aaebbb258bce30749fc302cbd161b78462252a32
author Gleb Koval <gleb@koval.net>
timestamp 0
Add test1.txt
""".trimIndent(),
commits[0].toString(),
)
}
@Test
fun `can display tree`() {
assertEquals(
"""
tree 048b8e267dd7a6c5d4849d59f6ff82e6ae948f13
+dir1/
| tree aaebbb258bce30749fc302cbd161b78462252a32
| +test1.txt
| | blob c57eff55ebc0c54973903af5f72bac72762cf4f4
| | | Hello World!
+dir2/
| tree 0e14cbdba02924cd63a58c2492fc3dd05dc682bd
| +test1.txt
| | blob da3fcc31cbc16fcbb7526d68771f77e7e7f02fb1
| | | This is a second file
""".trimIndent(),
commits[1].tree.toString(),
)
}
}