From 5e140edc3051741691e00bf96fa5119b44288a42 Mon Sep 17 00:00:00 2001 From: NAITOH Jun Date: Thu, 11 Jul 2024 09:49:56 +0900 Subject: [PATCH] Stop adding extra new line after XML declaration with pretty format (#164) If the XML file does not end with a newline, a space is added to the end of the first line. ```ruby Failure: test_indent(REXMLTests::TestDocument::WriteTest::ArgumentsTest) /Users/naitoh/ghq/github.com/naitoh/rexml/test/test_document.rb:270:in `test_indent' 267: output = "" 268: indent = 2 269: @document.write(output, indent) => 270: assert_equal(<<-EOX.chomp, output) 271: 272: 273: Hello world! <"\n" + "\n" + " Hello world!\n" + ""> expected but was <" \n" + "\n" + " Hello world!\n" + ""> diff: ? Hello world! ``` This is happen because `REXML::Formatters::Pretty#write_document` has a logic that depends on the last text node. We should ignore all top-level text nodes with pretty format. --- lib/rexml/formatters/pretty.rb | 2 +- test/test_document.rb | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/rexml/formatters/pretty.rb b/lib/rexml/formatters/pretty.rb index a1198b7a..a838d835 100644 --- a/lib/rexml/formatters/pretty.rb +++ b/lib/rexml/formatters/pretty.rb @@ -111,7 +111,7 @@ def write_document( node, output ) # itself, then we don't need a carriage return... which makes this # logic more complex. node.children.each { |child| - next if child == node.children[-1] and child.instance_of?(Text) + next if child.instance_of?(Text) unless child == node.children[0] or child.instance_of?(Text) or (child == node.children[1] and !node.children[0].writethis) output << "\n" diff --git a/test/test_document.rb b/test/test_document.rb index ec0e8a5a..9cd77c4e 100644 --- a/test/test_document.rb +++ b/test/test_document.rb @@ -236,7 +236,7 @@ def test_each_recursive class WriteTest < Test::Unit::TestCase def setup - @document = REXML::Document.new(<<-EOX) + @document = REXML::Document.new(<<-EOX.chomp) Hello world! EOX @@ -246,7 +246,7 @@ class ArgumentsTest < self def test_output output = "" @document.write(output) - assert_equal(<<-EOX, output) + assert_equal(<<-EOX.chomp, output) Hello world! EOX @@ -269,7 +269,7 @@ def test_transitive indent = 2 transitive = true @document.write(output, indent, transitive) - assert_equal(<<-EOX, output) + assert_equal(<<-EOX.chomp, output) Hello world! #{japanese_text} EOX @@ -309,7 +309,7 @@ class OptionsTest < self def test_output output = "" @document.write(:output => output) - assert_equal(<<-EOX, output) + assert_equal(<<-EOX.chomp, output) Hello world! EOX @@ -329,7 +329,7 @@ def test_indent def test_transitive output = "" @document.write(:output => output, :indent => 2, :transitive => true) - assert_equal(<<-EOX, output) + assert_equal(<<-EOX.chomp, output) Hello world! output, :encoding => encoding) - assert_equal(<<-EOX.encode(encoding), output) + assert_equal(<<-EOX.chomp.encode(encoding), output) #{japanese_text} EOX