Skip to content

Commit

Permalink
Fixed proper escaping of strings in YAML
Browse files Browse the repository at this point in the history
  • Loading branch information
darkfrog26 committed Nov 17, 2023
1 parent 9e69744 commit a32d477
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
18 changes: 18 additions & 0 deletions io/jvm/src/test/resources/formatted.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
one: 1
two: false
three: 3.5
four:
test1: 'Testing 1'
test2:
test3:
- 1
- 2
- 3
test4: |-
This
is
multi-line
test5: 'This is "quoted" text.'
test6:
-
test7: 'This isn''t going to fail!'
6 changes: 4 additions & 2 deletions io/jvm/src/test/scala/spec/YamlFormattingSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,13 @@ class YamlFormattingSpec extends AnyWordSpec with Matchers {
|is
|multi-line""".stripMargin,
"test5" -> "This is \"quoted\" text.",
"test6" -> arr(Null)
"test6" -> arr(Null),
"test7" -> "This isn't going to fail!"
)
)
val yamlString = YamlFormatter(v)
val expected = resource("formatted.yaml")
yamlString should be(expected)
val json = JsonParser(yamlString, Format.Yaml)
json should be(v)
}
Expand All @@ -70,7 +73,6 @@ class YamlFormattingSpec extends AnyWordSpec with Matchers {
val yamlString = resource(yamlName)
val json = JsonParser(jsonString)
val yaml = YamlFormatter(json)
println(yaml)
yaml should be(yamlString)
}

Expand Down
5 changes: 3 additions & 2 deletions io/shared/src/main/scala/fabric/io/YamlFormatter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ object YamlFormatter extends Formatter {

private def write(json: Json, depth: Int): String = {
def pad(adjust: Int = 0): String = "".padTo((depth + adjust) * 2, ' ')
def fix(s: String): String = s.replace("'", "''")
json match {
case Arr(v) =>
v.map(write(_, depth + 1)).map(s => s"${pad()}- ${s.dropWhile(_.isWhitespace)}").mkString("\n", "\n", "")
Expand All @@ -46,8 +47,8 @@ object YamlFormatter extends Formatter {
s"${pad()}$key:$v"
}
.mkString("\n", "\n", "")
case Str(s) if s.contains("\n") => s.split('\n').map(s => s"${pad()}$s").mkString("|-\n", "\n", "")
case Str(s) => s"'$s'"
case Str(s) if s.contains("\n") => fix(s).split('\n').map(s => s"${pad()}$s").mkString("|-\n", "\n", "")
case Str(s) => s"'${fix(s)}'"
}
}
}

0 comments on commit a32d477

Please sign in to comment.