Skip to content

Commit

Permalink
馃帀 tables are now aligned
Browse files Browse the repository at this point in the history
  • Loading branch information
jmfayard committed Aug 31, 2022
1 parent 88fab6b commit 1957d2f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
Expand Up @@ -2,6 +2,7 @@ package com.sksamuel.kotest.data

import io.kotest.assertions.throwables.shouldThrowMessage
import io.kotest.core.spec.style.FunSpec
import io.kotest.data.Row3
import io.kotest.data.headers
import io.kotest.data.mapRows
import io.kotest.data.row
Expand Down Expand Up @@ -149,8 +150,8 @@ class StringTableTest : FunSpec({
context("file.writeTable - success") {
val expectedFileContent = """
id | username | fullName
4 | jmfayard | Jean-Michel Fayard
6 | louis | Louis Caugnault
4 | jmfayard | Jean-Michel Fayard
6 | louis | Louis Caugnault
""".trim()

test("happy path") {
Expand All @@ -163,11 +164,31 @@ id | username | fullName
fileContent shouldBe expectedFileContent
}

test("columns should be aligned") {
fun row(i: Int): Row3<String, String, String> {
val value = "$i".repeat(i)
return row(value, value, value)
}

val table = table(
headers("a", "b", "c"),
row(2),
row(4),
row(6),
)
tempfile(suffix = ".table").writeTable(table.headers, table.rows) shouldBe """
a | b | c
22 | 22 | 22
4444 | 4444 | 4444
666666 | 666666 | 666666
""".trimIndent()
}

test("| should be escaped") {
val table = mapOf("greeting" to "Hello || world").toTable()
val file = tempfile(suffix = ".table")
file.writeTable(table.headers, table.rows) shouldBe """
key | value
key | value
greeting | Hello \|\| world
""".trimIndent()
}
Expand Down
Expand Up @@ -39,10 +39,27 @@ fun File.writeTable(headers: List<String>, cells: List<List<String>>): String {
if (extension != "table") throw AssertionError("Table file must have a .table extension")
val containsNewLines = cells.any { it.any { cell -> cell.contains("\n") } }
if (containsNewLines) throw AssertionError("Cells con't contain new lines")

val columnSizes = headers.mapIndexed { index, header ->
val rowsSize = cells.map { it[index].length }.maxOrNull() ?: 0
maxOf(header.length, rowsSize)
}

fun String.formatCell(index: Int) =
this.plus(" ".repeat(maxOf(0, columnSizes[index] - length)))

val separator = " | "
val formattedHeader = headers.joinToString(separator)

val formattedHeader = headers
.mapIndexed { index, header -> header.formatCell(index) }
.joinToString(separator)
.trimEnd()

val formattedContent = cells.joinToString("\n") { row ->
row.joinToString(separator) { it.replace("|", "\\|") }
val list = row.mapIndexed { index, cell ->
cell.replace("|", "\\|").formatCell(index)
}
list.joinToString(separator).trimEnd()
}

val fileContent = """
Expand Down

0 comments on commit 1957d2f

Please sign in to comment.