aboutsummaryrefslogtreecommitdiff
path: root/yamlesque/src/main/scala/YamlPrinter.scala
blob: 0a1c008e7be2c0175223cb0fc2736d14e5687891 (plain) (blame)
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
package yamlesque

import annotation.tailrec

class YamlPrinter(compact: Boolean = true) extends (YamlValue => String) {

  def apply(value: YamlValue): String = {
    val str = new StringBuilder()
    def p(value: YamlValue, indentation: Int): Unit = value match {
      case YamlScalar(value) =>
        str ++= "  " * indentation
        str ++= value
        str += '\n'
      case YamlSequence(items) =>
        for (item <- items) {
          str ++= "  " * indentation
          item match {
            case YamlScalar(v) if compact =>
              str ++= "- "
              str ++= v
              str += '\n'
            case _ =>
              str ++= "-\n"
              p(item, indentation + 1)
          }
        }
      case YamlMapping(fields) =>
        for ((key, value) <- fields) {
          str ++= "  " * indentation
          str ++= key
          value match {
            case YamlScalar(v) if compact =>
              str ++= ": "
              str ++= v
              str += '\n'
            case _ =>
              str ++= ":\n"
              p(value, indentation + 1)
          }
        }
    }
    p(value, 0)
    str.toString
  }

}