-
Notifications
You must be signed in to change notification settings - Fork 50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow customization of maxAliasesForCollections loader option #205
Merged
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2056442
add maxAliasForCollections override via Parser case class
hcdeng dc843c1
add tests
hcdeng 6439a42
fix test formatting
hcdeng 598039d
rename default parser
hcdeng c640bb0
fixes for scalastyle
hcdeng 27dbbf5
scalafmt
hcdeng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
package io.circe.yaml | ||
|
||
import cats.syntax.either._ | ||
import io.circe._ | ||
import java.io.{ Reader, StringReader } | ||
import org.yaml.snakeyaml.LoaderOptions | ||
import org.yaml.snakeyaml.Yaml | ||
import org.yaml.snakeyaml.constructor.SafeConstructor | ||
import org.yaml.snakeyaml.nodes._ | ||
import scala.collection.JavaConverters._ | ||
|
||
final case class Parser( | ||
maxAliasesForCollections: Int = 50 | ||
) { | ||
|
||
private val loaderOptions = { | ||
val options = new LoaderOptions() | ||
options.setMaxAliasesForCollections(maxAliasesForCollections) | ||
options | ||
} | ||
|
||
/** | ||
* Parse YAML from the given [[Reader]], returning either [[ParsingFailure]] or [[Json]] | ||
* @param yaml | ||
* @return | ||
*/ | ||
def parse(yaml: Reader): Either[ParsingFailure, Json] = for { | ||
parsed <- parseSingle(yaml) | ||
json <- yamlToJson(parsed) | ||
} yield json | ||
|
||
def parse(yaml: String): Either[ParsingFailure, Json] = parse(new StringReader(yaml)) | ||
|
||
def parseDocuments(yaml: Reader): Stream[Either[ParsingFailure, Json]] = parseStream(yaml).map(yamlToJson) | ||
def parseDocuments(yaml: String): Stream[Either[ParsingFailure, Json]] = parseDocuments(new StringReader(yaml)) | ||
|
||
private[this] def parseSingle(reader: Reader) = | ||
Either.catchNonFatal(new Yaml(loaderOptions).compose(reader)).leftMap(err => ParsingFailure(err.getMessage, err)) | ||
|
||
private[this] def parseStream(reader: Reader) = | ||
new Yaml(loaderOptions).composeAll(reader).asScala.toStream | ||
|
||
private[this] object CustomTag { | ||
def unapply(tag: Tag): Option[String] = if (!tag.startsWith(Tag.PREFIX)) | ||
Some(tag.getValue) | ||
else | ||
None | ||
} | ||
|
||
private[this] class FlatteningConstructor extends SafeConstructor { | ||
def flatten(node: MappingNode): MappingNode = { | ||
flattenMapping(node) | ||
node | ||
} | ||
|
||
def construct(node: ScalarNode): Object = | ||
getConstructor(node).construct(node) | ||
} | ||
|
||
private[this] def yamlToJson(node: Node): Either[ParsingFailure, Json] = { | ||
// Isn't thread-safe internally, may hence not be shared | ||
val flattener: FlatteningConstructor = new FlatteningConstructor | ||
|
||
def convertScalarNode(node: ScalarNode) = Either | ||
.catchNonFatal(node.getTag match { | ||
case Tag.INT if node.getValue.startsWith("0x") || node.getValue.contains("_") => | ||
Json.fromJsonNumber(flattener.construct(node) match { | ||
case int: Integer => JsonLong(int.toLong) | ||
case long: java.lang.Long => JsonLong(long) | ||
case bigint: java.math.BigInteger => | ||
JsonDecimal(bigint.toString) | ||
case other => throw new NumberFormatException(s"Unexpected number type: ${other.getClass}") | ||
}) | ||
case Tag.INT | Tag.FLOAT => | ||
JsonNumber.fromString(node.getValue).map(Json.fromJsonNumber).getOrElse { | ||
throw new NumberFormatException(s"Invalid numeric string ${node.getValue}") | ||
} | ||
case Tag.BOOL => | ||
Json.fromBoolean(flattener.construct(node) match { | ||
case b: java.lang.Boolean => b | ||
case _ => throw new IllegalArgumentException(s"Invalid boolean string ${node.getValue}") | ||
}) | ||
case Tag.NULL => Json.Null | ||
case CustomTag(other) => | ||
Json.fromJsonObject(JsonObject.singleton(other.stripPrefix("!"), Json.fromString(node.getValue))) | ||
case other => Json.fromString(node.getValue) | ||
}) | ||
.leftMap { err => | ||
ParsingFailure(err.getMessage, err) | ||
} | ||
|
||
def convertKeyNode(node: Node) = node match { | ||
case scalar: ScalarNode => Right(scalar.getValue) | ||
case _ => Left(ParsingFailure("Only string keys can be represented in JSON", null)) | ||
} | ||
|
||
if (node == null) { | ||
Right(Json.False) | ||
} else { | ||
node match { | ||
case mapping: MappingNode => | ||
flattener | ||
.flatten(mapping) | ||
.getValue | ||
.asScala | ||
.foldLeft( | ||
Either.right[ParsingFailure, JsonObject](JsonObject.empty) | ||
) { (objEither, tup) => | ||
for { | ||
obj <- objEither | ||
key <- convertKeyNode(tup.getKeyNode) | ||
value <- yamlToJson(tup.getValueNode) | ||
} yield obj.add(key, value) | ||
} | ||
.map(Json.fromJsonObject) | ||
case sequence: SequenceNode => | ||
sequence.getValue.asScala | ||
.foldLeft(Either.right[ParsingFailure, List[Json]](List.empty[Json])) { (arrEither, node) => | ||
for { | ||
arr <- arrEither | ||
value <- yamlToJson(node) | ||
} yield value :: arr | ||
} | ||
.map(arr => Json.fromValues(arr.reverse)) | ||
case scalar: ScalarNode => convertScalarNode(scalar) | ||
} | ||
} | ||
} | ||
} | ||
|
||
object Parser { | ||
val defaultParser = Parser() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,120 +1,19 @@ | ||
package io.circe.yaml | ||
|
||
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._ | ||
|
||
package object parser { | ||
import java.io.Reader | ||
|
||
package object parser { | ||
/** | ||
* Parse YAML from the given [[Reader]], returning either [[ParsingFailure]] or [[Json]] | ||
* @param yaml | ||
* @return | ||
*/ | ||
def parse(yaml: Reader): Either[ParsingFailure, Json] = for { | ||
parsed <- parseSingle(yaml) | ||
json <- yamlToJson(parsed) | ||
} yield json | ||
|
||
def parse(yaml: String): Either[ParsingFailure, Json] = parse(new StringReader(yaml)) | ||
|
||
def parseDocuments(yaml: Reader): Stream[Either[ParsingFailure, Json]] = parseStream(yaml).map(yamlToJson) | ||
def parseDocuments(yaml: String): Stream[Either[ParsingFailure, Json]] = parseDocuments(new StringReader(yaml)) | ||
|
||
private[this] def parseSingle(reader: Reader) = | ||
Either.catchNonFatal(new Yaml().compose(reader)).leftMap(err => ParsingFailure(err.getMessage, err)) | ||
|
||
private[this] def parseStream(reader: Reader) = | ||
new Yaml().composeAll(reader).asScala.toStream | ||
|
||
private[this] object CustomTag { | ||
def unapply(tag: Tag): Option[String] = if (!tag.startsWith(Tag.PREFIX)) | ||
Some(tag.getValue) | ||
else | ||
None | ||
} | ||
|
||
private[this] class FlatteningConstructor extends SafeConstructor { | ||
def flatten(node: MappingNode): MappingNode = { | ||
flattenMapping(node) | ||
node | ||
} | ||
|
||
def construct(node: ScalarNode): Object = | ||
getConstructor(node).construct(node) | ||
} | ||
|
||
private[this] def yamlToJson(node: Node): Either[ParsingFailure, Json] = { | ||
// Isn't thread-safe internally, may hence not be shared | ||
val flattener: FlatteningConstructor = new FlatteningConstructor | ||
|
||
def convertScalarNode(node: ScalarNode) = Either | ||
.catchNonFatal(node.getTag match { | ||
case Tag.INT if node.getValue.startsWith("0x") || node.getValue.contains("_") => | ||
Json.fromJsonNumber(flattener.construct(node) match { | ||
case int: Integer => JsonLong(int.toLong) | ||
case long: java.lang.Long => JsonLong(long) | ||
case bigint: java.math.BigInteger => | ||
JsonDecimal(bigint.toString) | ||
case other => throw new NumberFormatException(s"Unexpected number type: ${other.getClass}") | ||
}) | ||
case Tag.INT | Tag.FLOAT => | ||
JsonNumber.fromString(node.getValue).map(Json.fromJsonNumber).getOrElse { | ||
throw new NumberFormatException(s"Invalid numeric string ${node.getValue}") | ||
} | ||
case Tag.BOOL => | ||
Json.fromBoolean(flattener.construct(node) match { | ||
case b: java.lang.Boolean => b | ||
case _ => throw new IllegalArgumentException(s"Invalid boolean string ${node.getValue}") | ||
}) | ||
case Tag.NULL => Json.Null | ||
case CustomTag(other) => | ||
Json.fromJsonObject(JsonObject.singleton(other.stripPrefix("!"), Json.fromString(node.getValue))) | ||
case other => Json.fromString(node.getValue) | ||
}) | ||
.leftMap { err => | ||
ParsingFailure(err.getMessage, err) | ||
} | ||
def parse(yaml: Reader): Either[ParsingFailure, Json] = Parser.defaultParser.parse(yaml) | ||
|
||
def convertKeyNode(node: Node) = node match { | ||
case scalar: ScalarNode => Right(scalar.getValue) | ||
case _ => Left(ParsingFailure("Only string keys can be represented in JSON", null)) | ||
} | ||
def parse(yaml: String): Either[ParsingFailure, Json] = Parser.defaultParser.parse(yaml) | ||
|
||
if (node == null) { | ||
Right(Json.False) | ||
} else { | ||
node match { | ||
case mapping: MappingNode => | ||
flattener | ||
.flatten(mapping) | ||
.getValue | ||
.asScala | ||
.foldLeft( | ||
Either.right[ParsingFailure, JsonObject](JsonObject.empty) | ||
) { (objEither, tup) => | ||
for { | ||
obj <- objEither | ||
key <- convertKeyNode(tup.getKeyNode) | ||
value <- yamlToJson(tup.getValueNode) | ||
} yield obj.add(key, value) | ||
} | ||
.map(Json.fromJsonObject) | ||
case sequence: SequenceNode => | ||
sequence.getValue.asScala | ||
.foldLeft(Either.right[ParsingFailure, List[Json]](List.empty[Json])) { (arrEither, node) => | ||
for { | ||
arr <- arrEither | ||
value <- yamlToJson(node) | ||
} yield value :: arr | ||
} | ||
.map(arr => Json.fromValues(arr.reverse)) | ||
case scalar: ScalarNode => convertScalarNode(scalar) | ||
} | ||
} | ||
} | ||
def parseDocuments(yaml: Reader): Stream[Either[ParsingFailure, Json]] = Parser.defaultParser.parseDocuments(yaml) | ||
def parseDocuments(yaml: String): Stream[Either[ParsingFailure, Json]] = Parser.defaultParser.parseDocuments(yaml) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Kind of nitpicky, but can we rename this to
default
(which follows the naming convention in e.g. circe-generic-extras) and put an explicit type annotation on it?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yup, updated