You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/09/03 06:08:35 UTC
(groovy) 02/02: GROOVY-12347: DomToGroovy: escape document text on its way into generated source
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 0a2d6ac61f035d5875efbe3f2fd1f32482ad93a7
Author: Paul King <pa...@asert.com.au>
AuthorDate: Thu Sep 3 14:13:05 2026 +1000
GROOVY-12347: DomToGroovy: escape document text on its way into generated source
Three places wrote document content into the generated script without
escaping it, so text that was ordinary in XML became syntax in Groovy.
printQuoted escaped the single-line branch and not the triple-quoted one,
where a backslash still starts an escape sequence: XML text holding a
Windows path round-tripped as a tab, a newline and the remains of the
path, and text holding three quotes produced source that did not compile.
It now escapes backslashes, and quotes only where they would run into the
closing delimiter, so apostrophes in prose stay readable.
printComment wrote a comment's data into a Groovy block comment, so a
comment carrying the terminator closed it early and left the rest of the
document standing as code. The terminator is now broken up.
printPI placed a processing instruction's target and data between quotes
it did not escape. Both now go through printQuoted, which quotes them,
escapes them, and handles data spanning lines.
The class javadoc described a SAX handler; the class takes a DOM Document
and produces MarkupBuilder calls to read and edit. It now says so, and
says that generating from a document and evaluating the result runs
whatever that document produced.
The user guide offered the conversion as a way to "automate generation"
and demonstrated evaluating the output directly. It now presents the tool
as an authoring aid whose output is a starting point, and qualifies the
evaluation in the example. Its class name and package were left over from
before the 2019 rename.
---
.../org/apache/groovy/xml/tools/DomToGroovy.java | 46 ++++++++++++++---
.../groovy-xml/src/spec/doc/xml-userguide.adoc | 18 ++++---
.../apache/groovy/xml/tools/DomToGroovyTest.groovy | 57 ++++++++++++++++++++++
3 files changed, 107 insertions(+), 14 deletions(-)
diff --git a/subprojects/groovy-xml/src/main/java/org/apache/groovy/xml/tools/DomToGroovy.java b/subprojects/groovy-xml/src/main/java/org/apache/groovy/xml/tools/DomToGroovy.java
index 535f509425..657b7c721d 100644
--- a/subprojects/groovy-xml/src/main/java/org/apache/groovy/xml/tools/DomToGroovy.java
+++ b/subprojects/groovy-xml/src/main/java/org/apache/groovy/xml/tools/DomToGroovy.java
@@ -47,7 +47,14 @@ import java.util.HashMap;
import java.util.Map;
/**
- * A SAX handler for turning XML into Groovy scripts
+ * Turns a DOM document into the {@link groovy.xml.MarkupBuilder} calls that would produce
+ * it, as an aid to writing builder code by hand. The result is a starting point to edit
+ * rather than a finished script: names that are not valid Groovy identifiers are quoted,
+ * and the layout is meant to be read.
+ * <p>
+ * The output is Groovy source. Generating it from a document and then evaluating it runs
+ * whatever that document produced, so generation belongs in authoring, not in a runtime
+ * path fed by documents the author does not control.
*/
public class DomToGroovy {
@@ -289,7 +296,7 @@ public class DomToGroovy {
protected void printQuoted(String text) {
if (text.contains("\n")) {
print("'''");
- print(text);
+ print(escapeTripleQuote(text));
print("'''");
} else {
print(qt);
@@ -306,11 +313,11 @@ public class DomToGroovy {
*/
protected void printPI(ProcessingInstruction instruction, boolean endWithComma) {
printIndent();
- print("mkp.pi(" + qt);
- print(instruction.getTarget());
- print(qt + ", " + qt);
- print(instruction.getData());
- printEnd(qt + ");", endWithComma);
+ print("mkp.pi(");
+ printQuoted(instruction.getTarget());
+ print(", ");
+ printQuoted(instruction.getData());
+ printEnd(");", endWithComma);
}
/**
@@ -324,7 +331,9 @@ public class DomToGroovy {
if (!text.isEmpty()) {
printIndent();
print("/* ");
- print(text);
+ // a comment carrying the block-comment terminator would close this comment
+ // early and leave the rest of the document standing as code
+ print(text.replace("*/", "* /"));
printEnd(" */", endWithComma);
}
}
@@ -355,6 +364,27 @@ public class DomToGroovy {
return text.replaceAll("\\\\", "\\\\\\\\").replaceAll(qt, "\\\\" + qt);
}
+ /**
+ * Escapes text for a triple-quoted Groovy string literal. A backslash always starts an
+ * escape sequence and so needs escaping; a quote needs it only where it would otherwise
+ * run into the closing delimiter, which leaves apostrophes in ordinary prose alone.
+ *
+ * @param text raw text
+ * @return escaped text
+ */
+ protected String escapeTripleQuote(String text) {
+ String escaped = text.replace("\\", "\\\\");
+ StringBuilder result = new StringBuilder(escaped.length());
+ for (int i = 0; i < escaped.length(); i += 1) {
+ char c = escaped.charAt(i);
+ if (c == '\'' && (i + 1 == escaped.length() || escaped.charAt(i + 1) == '\'')) {
+ result.append('\\');
+ }
+ result.append(c);
+ }
+ return result.toString();
+ }
+
/**
* Returns the namespace map extended with any newly encountered element or attribute prefixes.
*
diff --git a/subprojects/groovy-xml/src/spec/doc/xml-userguide.adoc b/subprojects/groovy-xml/src/spec/doc/xml-userguide.adoc
index 79fb376409..cee46193d7 100644
--- a/subprojects/groovy-xml/src/spec/doc/xml-userguide.adoc
+++ b/subprojects/groovy-xml/src/spec/doc/xml-userguide.adoc
@@ -510,20 +510,26 @@ include::../test/UserGuideStreamingMarkupBuilderTest.groovy[tags=testMkp,indent=
`mkp.yield`
<2> Checking the values later on with `XmlSlurper`
-=== DOMToGroovy
+=== DomToGroovy
-Suppose we have an existing XML document and we want to automate
-generation of the markup without having to type it all in? We just
-need to use `org.codehaus.groovy.tools.xml.DOMToGroovy` as shown in
+Suppose we have an existing XML document and we want a head start on
+writing the markup rather than typing it all in? We just
+need to use `org.apache.groovy.xml.tools.DomToGroovy` as shown in
the following example:
+`DomToGroovy` is an authoring aid. It produces builder code to read and edit,
+so the generated source is a starting point rather than a finished script.
+The example below evaluates it directly to show that the round trip works;
+do that only for documents you control, since evaluating generated source
+runs whatever the document produced.
+
[source,groovy]
-.Building MarkupBuilder from DOMToGroovy
+.Building MarkupBuilder from DomToGroovy
----
include::../test/UserGuideMarkupBuilderTest.groovy[tags=testDOMToGroovy,indent=0]
----
-<1> Creating `DOMToGroovy` instance
+<1> Creating `DomToGroovy` instance
<2> Converts the XML to `MarkupBuilder` calls which are available in the output `StringWriter`
<3> Using `output` variable to create the whole MarkupBuilder
<4> Back to XML string
diff --git a/subprojects/groovy-xml/src/test/groovy/org/apache/groovy/xml/tools/DomToGroovyTest.groovy b/subprojects/groovy-xml/src/test/groovy/org/apache/groovy/xml/tools/DomToGroovyTest.groovy
index a5478859dd..dcb8c3b818 100644
--- a/subprojects/groovy-xml/src/test/groovy/org/apache/groovy/xml/tools/DomToGroovyTest.groovy
+++ b/subprojects/groovy-xml/src/test/groovy/org/apache/groovy/xml/tools/DomToGroovyTest.groovy
@@ -19,6 +19,7 @@
package org.apache.groovy.xml.tools
import groovy.test.StringTestUtil
+import groovy.xml.XmlSlurper
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.w3c.dom.Document
@@ -107,6 +108,62 @@ class DomToGroovyTest {
checkConversion(TEST_XML_5, EXPECTED_BUILDER_SCRIPT_5)
}
+ @Test
+ void multilineTextSurvivesTheRoundTrip() {
+ // multi-line content is emitted in a triple-quoted literal, where a backslash
+ // still starts an escape sequence and a run of quotes can close the literal early
+ ['line one\nC:\\temp\\new',
+ 'line one\n' + "'" * 3,
+ "line one\nends with a quote'",
+ "line one\ndon't touch ordinary prose"].each { text ->
+ assert roundTrip(text) == text
+ }
+ }
+
+ @Test
+ void apostrophesInProseAreNotEscaped() {
+ // the generated source is meant to be read and edited, so only quotes that would
+ // run into the closing delimiter are escaped
+ assert generate("line one\ndon't split ordinary prose").contains("don't split")
+ }
+
+ @Test
+ void commentContentCannotCloseTheGeneratedComment() {
+ String generated = generateFrom('<a><!-- */ marker() /* --><b>ok</b></a>')
+ assert !generated.contains('*/ marker')
+ assert generated.contains('* /')
+ }
+
+ @Test
+ void processingInstructionDataIsQuoted() {
+ String generated = generateFrom("<a><?target it's data?><b>ok</b></a>")
+ // the apostrophe must not close the literal the data sits in
+ assert generated.contains("it\\'s data")
+ }
+
+ private String generateFrom(String xml) {
+ Document document = builder.parse(new ByteArrayInputStream(xml.bytes))
+ StringWriter writer = new StringWriter()
+ new DomToGroovy(new PrintWriter(writer)).print(document)
+ writer.toString().trim()
+ }
+
+ private String roundTrip(String text) {
+ String recovered = new GroovyShell().evaluate(
+ 'def out = new StringWriter()\n' +
+ 'def mb = new groovy.xml.MarkupBuilder(out)\n' +
+ 'mb.' + generate(text) + '\n' +
+ 'out.toString()')
+ new XmlSlurper().parseText(recovered).b.text()
+ }
+
+ private String generate(String text) {
+ Document document = builder.parse(new ByteArrayInputStream("<a><b>${text}</b></a>".bytes))
+ StringWriter writer = new StringWriter()
+ new DomToGroovy(new PrintWriter(writer)).print(document)
+ writer.toString().trim()
+ }
+
private void checkConversion(String testXml, String expectedScript) throws SAXException, IOException {
ByteArrayInputStream inputStream = new ByteArrayInputStream(testXml.getBytes())
Document document = builder.parse(inputStream)