diff --git a/io/jvm/src/test/resources/formatted.yaml b/io/jvm/src/test/resources/formatted.yaml new file mode 100644 index 0000000..364250a --- /dev/null +++ b/io/jvm/src/test/resources/formatted.yaml @@ -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!' \ No newline at end of file diff --git a/io/jvm/src/test/scala/spec/YamlFormattingSpec.scala b/io/jvm/src/test/scala/spec/YamlFormattingSpec.scala index a423cff..4b6796f 100644 --- a/io/jvm/src/test/scala/spec/YamlFormattingSpec.scala +++ b/io/jvm/src/test/scala/spec/YamlFormattingSpec.scala @@ -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) } @@ -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) } diff --git a/io/shared/src/main/scala/fabric/io/YamlFormatter.scala b/io/shared/src/main/scala/fabric/io/YamlFormatter.scala index 1b60a23..fdc7b52 100644 --- a/io/shared/src/main/scala/fabric/io/YamlFormatter.scala +++ b/io/shared/src/main/scala/fabric/io/YamlFormatter.scala @@ -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", "") @@ -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)}'" } } }