-
Notifications
You must be signed in to change notification settings - Fork 22
/
Yaml.scala
68 lines (59 loc) · 2.06 KB
/
Yaml.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
62
63
64
65
66
67
68
package org.virtuslab
import org.virtuslab.yaml.internal.dump.present.PresenterImpl
import org.virtuslab.yaml.internal.dump.serialize.SerializerImpl
import org.virtuslab.yaml.internal.load.compose.ComposerImpl
import org.virtuslab.yaml.internal.load.parse.Parser
import org.virtuslab.yaml.internal.load.parse.ParserImpl
import org.virtuslab.yaml.internal.load.reader.Tokenizer
package object yaml {
implicit class StringOps(val str: String) extends AnyVal {
/**
* Parse YAML from the given [[String]], returning either [[YamlError]] or [[T]].
*
* According to the specification:
* - [[Parser]] takes input string and produces sequence of events
* - then [[Composer]] produces a representation graph from events
* - finally [[YamlDecoder]] (construct phase from the YAML spec) constructs data type [[T]] from the YAML representation.
*/
def as[T](implicit
c: YamlDecoder[T],
settings: LoadSettings = LoadSettings.empty
): Either[YamlError, T] =
for {
events <- {
val parser = ParserImpl(Tokenizer.make(str))
parser.getEvents()
}
node <- ComposerImpl.fromEvents(events)
t <- node.as[T]
} yield t
def asNode: Either[YamlError, Node] =
for {
events <- {
val parser = ParserImpl(Tokenizer.make(str))
parser.getEvents()
}
node <- ComposerImpl.fromEvents(events)
} yield node
}
implicit class AnyOps[T](val t: T) extends AnyVal {
/**
* Serialize a [[T]] into a YAML string.
*
* According to the specification:
* - [[YamlEncoder]] encode type [[T]] into [[Node]]
* - [[Serializer]] serializes [[Node]] into sequence of [[Event]]s
* - [[Presenter]] present [[Events]] as a character stream
*/
def asYaml(implicit encoder: YamlEncoder[T]): String = {
val node = encoder.asNode(t)
node.asYaml
}
}
implicit class NodeOps(val node: Node) extends AnyVal {
def asYaml: String = {
val events = SerializerImpl.toEvents(node)
PresenterImpl.asString(events)
}
}
}