-
Notifications
You must be signed in to change notification settings - Fork 1
/
PrettyPrint.scala
62 lines (50 loc) · 1.47 KB
/
PrettyPrint.scala
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 wvlet.core.tablet.text
import java.nio.charset.StandardCharsets
import org.msgpack.value.Variable
import wvlet.core.tablet.obj.ObjectTabletReader
import wvlet.log.LogSupport
import wvlet.obj.ObjectSchema
/**
*
*/
object PrettyPrint extends LogSupport {
def show[A](seq:Seq[A], limit:Int=20) {
pp(seq.take(limit))
}
def pp[A](seq:Seq[A]) {
info(pf(seq).mkString("\n"))
}
def pf[A](seq:Seq[A]) : Seq[String] = {
val b = Seq.newBuilder[Seq[String]]
val paramNames = seq.headOption.map { x =>
val schema = ObjectSchema(x.getClass)
b += schema.parameters.map(_.name).toSeq
}
val reader = new ObjectTabletReader(seq)
b ++= (reader | RecordPrinter)
val rows = b.result
val colWidth = maxColWidths(rows)
val s = Seq.newBuilder[String]
for(r <- rows) {
val cols = for((c, i) <- r.zipWithIndex) yield pad(c, colWidth(i))
s += cols.mkString(" ")
}
s.result()
}
def screenTextLength(s:String) : Int = {
(for (i <- 0 until s.length) yield {
val ch = s.charAt(i)
if (ch < 128) 1 else 2
}).sum
}
def maxColWidths(rows:Seq[Seq[String]]) : IndexedSeq[Int] = {
val maxWidth = (0 until rows.length).map(i => 0).toArray
for(r <- rows; (c, i) <- r.zipWithIndex) {
maxWidth(i) = math.max(screenTextLength(c), maxWidth(i))
}
maxWidth.toIndexedSeq
}
def pad(s:String, colWidth:Int) : String = {
(" " * Math.max(0, colWidth - screenTextLength(s))) + s
}
}