summaryrefslogtreecommitdiff
path: root/crashboxd/src/main/scala/io/crashbox/ci/yaml/Yaml.scala
blob: 0370c76f396c3bef971a60442d134e4457276a87 (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
package io.crashbox.ci
package yaml

import java.util.{List => JList, Map => JMap}

import scala.collection.JavaConverters._

import org.yaml.snakeyaml.{DumperOptions, Yaml => SYaml}
import org.yaml.snakeyaml.constructor.Constructor
import org.yaml.snakeyaml.representer.Representer
import org.yaml.snakeyaml.resolver.Resolver

object Yaml {

  private def toYaml(yml: Any): YamlValue = yml match {
    case m: JMap[_, _] =>
      YamlMap(m.asScala.toMap.map { case (k, v) => k.toString -> toYaml(v) })
    case l: JList[_] => YamlSeq(l.asScala.toList.map(toYaml(_)))
    case s: String => YamlString(s)
    case other => throw new YamlFormatException("Unknown YAML type: " + other)
  }

  /** Strict parsing */
  def parse(data: String): YamlValue = {
    val resolver = new Resolver {
      override def addImplicitResolvers: Unit = {}
    }
    val yml = new SYaml(new Constructor(),
                        new Representer(),
                        new DumperOptions(),
                        resolver)
    val node = yml.load(data)
    toYaml(node)
  }

}