Skip to content

Commit

Permalink
Merge pull request #32 from travisbrown/fix/31
Browse files Browse the repository at this point in the history
Support merge keys
  • Loading branch information
jeremyrsmith authored Jun 9, 2017
2 parents a27c48f + c06cdf2 commit befb2b6
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/main/scala/io/circe/yaml/parser/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import cats.syntax.either._
import io.circe._
import java.io.{Reader, StringReader}
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor.SafeConstructor
import org.yaml.snakeyaml.nodes._
import scala.collection.JavaConverters._

Expand Down Expand Up @@ -38,6 +39,15 @@ package object parser {
None
}

private[this] class FlatteningConstructor extends SafeConstructor {
def flatten(node: MappingNode): MappingNode = {
flattenMapping(node)
node
}
}

private[this] val flattener: FlatteningConstructor = new FlatteningConstructor

private[this] def yamlToJson(node: Node): Either[ParsingFailure, Json] = {

def convertScalarNode(node: ScalarNode) = Either.catchNonFatal(node.getTag match {
Expand All @@ -61,7 +71,9 @@ package object parser {

node match {
case mapping: MappingNode =>
mapping.getValue.asScala.foldLeft(Either.right[ParsingFailure, JsonObject](JsonObject.empty)) {
flattener.flatten(mapping).getValue.asScala.foldLeft(
Either.right[ParsingFailure, JsonObject](JsonObject.empty)
) {
(objEither, tup) => for {
obj <- objEither
key <- convertKeyNode(tup.getKeyNode)
Expand Down
40 changes: 40 additions & 0 deletions src/test/resources/test-yamls/merge-key.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
[
{
"x" : 1,
"y" : 2
},
{
"x" : 0,
"y" : 2
},
{
"r" : 1e1
},
{
"r" : 1
},
{
"x" : 1,
"y" : 2,
"r" : 1e1,
"label" : "center/big"
},
{
"x" : 1,
"y" : 2,
"r" : 1e1,
"label" : "center/big"
},
{
"x" : 1,
"y" : 2,
"r" : 1e1,
"label" : "center/big"
},
{
"r" : 1e1,
"x" : 1,
"y" : 2,
"label" : "center/big"
}
]
27 changes: 27 additions & 0 deletions src/test/resources/test-yamls/merge-key.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }

# All the following maps are equal:

- # Explicit keys
x: 1
y: 2
r: 10
label: center/big

- # Merge one map
<< : *CENTER
r: 10
label: center/big

- # Merge multiple maps
<< : [ *CENTER, *BIG ]
label: center/big

- # Override
<< : [ *BIG, *LEFT, *SMALL ]
x: 1
label: center/big

0 comments on commit befb2b6

Please sign in to comment.