From 37a3869ff6577448a81aff6c82397ef39a725834 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Mon, 23 Nov 2026 22:11:22 +0300 Subject: [PATCH] Edit the .idea XML files with the JDK's DOM instead of Groovy's XmlParser XmlUtils and ConfigureJavaFormatterXml read and wrote .idea/open-java-format.xml, workspace.xml and externalDependencies.xml with Groovy's XmlParser, XmlNodePrinter and groovy.util.Node. The plugin does not declare Groovy: it came with gradleApi() at compile time and, at run time, from the Groovy that the build's Gradle bundles, which once already dropped groovy.util.XmlParser. They parse with the JDK's DocumentBuilder now and edit the DOM. The DOM keeps an element's attributes sorted by name, so a second pass with SAX records the order of the file. A printer of the plugin's own writes the files as IntelliJ does: the XML declaration, two spaces of indentation, a space before "/>", the attributes in the order of the file and those added after them, and no line break at the end. Text and CDATA come out as they are. The files are written in UTF-8, which IntelliJ reads, rather than in the JVM's default charset. A file is written only when what the printer makes of it changes, so a file with nothing to change keeps its bytes, however it was written. Before, the plugin rewrote each file every time its task ran. A min-version="" counts as none now; Version.parse("") failed the task. Fixes #262. --- .../gradle/ConfigureJavaFormatterXml.java | 77 +++--- .../palantir/javaformat/gradle/XmlUtils.java | 253 ++++++++++++++++-- .../gradle/ConfigureJavaFormatterXmlTest.java | 120 ++++----- .../gradle/RequiredIdeaPluginTest.java | 2 +- .../javaformat/gradle/XmlUtilsTest.java | 234 ++++++++++++++++ 5 files changed, 562 insertions(+), 124 deletions(-) create mode 100644 gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/XmlUtilsTest.java diff --git a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/ConfigureJavaFormatterXml.java b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/ConfigureJavaFormatterXml.java index d647235e8..723ea592c 100644 --- a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/ConfigureJavaFormatterXml.java +++ b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/ConfigureJavaFormatterXml.java @@ -16,67 +16,66 @@ package com.palantir.javaformat.gradle; -import groovy.util.Node; import java.lang.module.ModuleDescriptor; import java.net.URI; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import org.w3c.dom.Element; final class ConfigureJavaFormatterXml { - static void configureJavaFormat(Node rootNode, List uris) { + static void configureJavaFormat(Element rootNode, List uris) { var settings = matchOrCreateChild(rootNode, "component", Map.of("name", "PalantirJavaFormatSettings")); // enable - attributes(matchOrCreateChild(settings, "option", Map.of("name", "enabled"))) - .put("value", "true"); + matchOrCreateChild(settings, "option", Map.of("name", "enabled")).setAttribute("value", "true"); // configure classpath var classPath = matchOrCreateChild(settings, "option", Map.of("name", "implementationClassPath")); var listItems = matchOrCreateChild(classPath, "list", Map.of()); - listItems.children().clear(); + for (var child : XmlUtils.children(listItems)) { + listItems.removeChild(child); + } for (var uri : uris) { - listItems.appendNode("option", new LinkedHashMap<>(Map.of("value", uri.toString()))); + appendChild(listItems, "option", Map.of("value", uri.toString())); } // Earlier versions wrote the native binary for openjavaformat.native.formatter=true. The IDE plugin has a // setting of its own for that now, useNativeImage, which is left alone, and no longer reads this option. - matchChild(settings, "option", Map.of("name", "nativeImageClassPath")) - .ifPresent(option -> option.parent().remove(option)); + matchChild(settings, "option", Map.of("name", "nativeImageClassPath")).ifPresent(settings::removeChild); } - static void configureWorkspaceXml(Node rootNode) { + static void configureWorkspaceXml(Element rootNode) { configureFormatOnSave(rootNode); configureOptimizeOnSave(rootNode); } // Lists an IDEA plugin as required by the project, so IntelliJ offers to install or update it. The other // required plugins stay, and so does a higher min-version for this one, such as a developer's own choice. - static void configureExternalDependencies(Node rootNode, String pluginId, String minVersion) { + static void configureExternalDependencies(Element rootNode, String pluginId, String minVersion) { var externalDependencies = matchOrCreateChild(rootNode, "component", Map.of("name", "ExternalDependencies")); var plugin = matchOrCreateChild(externalDependencies, "plugin", Map.of("id", pluginId)); - var existing = plugin.attribute("min-version"); + // Empty when the plugin is listed without one. + var existing = plugin.getAttribute("min-version"); var required = ModuleDescriptor.Version.parse(minVersion); - if (existing == null - || ModuleDescriptor.Version.parse(existing.toString()).compareTo(required) < 0) { - attributes(plugin).put("min-version", minVersion); + if (existing.isEmpty() || ModuleDescriptor.Version.parse(existing).compareTo(required) < 0) { + plugin.setAttribute("min-version", minVersion); } } - private static void configureFormatOnSave(Node rootNode) { + private static void configureFormatOnSave(Element rootNode) { configureOnSaveAction(matchOrCreateChild(rootNode, "component", Map.of("name", "FormatOnSaveOptions"))); } - private static void configureOptimizeOnSave(Node rootNode) { + private static void configureOptimizeOnSave(Element rootNode) { configureOnSaveAction(matchOrCreateChild(rootNode, "component", Map.of("name", "OptimizeOnSaveOptions"))); } - private static void configureOnSaveAction(Node onSaveOptions) { + private static void configureOnSaveAction(Element onSaveOptions) { // In IntelliJ <2023.3.7, the myRunOnSave option is default false. // In IntelliJ >=2023.3.7, it is default true, and if it is set to true IntelliJ will remove it from the XML // the next time the file is saved or the actions on save options window is saved. // So to cover all cases, we always write it out and ensure it is true - var myRunOnSave = matchOrCreateChild(onSaveOptions, "option", Map.of("name", "myRunOnSave")); - attributes(myRunOnSave).put("value", "true"); + matchOrCreateChild(onSaveOptions, "option", Map.of("name", "myRunOnSave")) + .setAttribute("value", "true"); // In IntelliJ <2023.3.7, the myAllFileTypesSelected option is default true. // In IntelliJ >=2023.3.7, it is default false, and if it is set to false IntelliJ will remove it from the XML @@ -91,33 +90,39 @@ private static void configureOnSaveAction(Node onSaveOptions) { matchOrCreateChild(set, "option", Map.of("value", "JAVA")); } - private static Node matchOrCreateChild(Node base, String name, Map attributes) { + private static Element matchOrCreateChild(Element base, String name, Map attributes) { return matchOrCreateChild(base, name, attributes, Map.of()); } // A new child gets the defaults too; an existing one is left as it is. - private static Node matchOrCreateChild( - Node base, String name, Map attributes, Map defaults) { + private static Element matchOrCreateChild( + Element base, String name, Map attributes, Map defaults) { return matchChild(base, name, attributes).orElseGet(() -> { - // The node keeps this map and the callers put values in it, so it has to be mutable. - var newAttributes = new LinkedHashMap<>(attributes); - newAttributes.putAll(defaults); - return base.appendNode(name, newAttributes); + var child = appendChild(base, name, attributes); + defaults.forEach(child::setAttribute); + return child; }); } - private static Optional matchChild(Node base, String name, Map attributes) { - // The children with that name, in a NodeList. - var children = (List) base.get(name); - return children.stream() - .map(Node.class::cast) - .filter(child -> attributes(child).entrySet().containsAll(attributes.entrySet())) + private static Element appendChild(Element base, String name, Map attributes) { + var child = base.getOwnerDocument().createElement(name); + attributes.forEach(child::setAttribute); + base.appendChild(child); + return child; + } + + private static Optional matchChild(Element base, String name, Map attributes) { + return XmlUtils.children(base).stream() + .filter(Element.class::isInstance) + .map(Element.class::cast) + .filter(child -> child.getTagName().equals(name) && hasAttributes(child, attributes)) .findFirst(); } - // Node.attributes() is a raw Map. - private static Map attributes(Node node) { - return node.attributes(); + private static boolean hasAttributes(Element element, Map attributes) { + return attributes.entrySet().stream() + .allMatch(attribute -> element.hasAttribute(attribute.getKey()) + && element.getAttribute(attribute.getKey()).equals(attribute.getValue())); } private ConfigureJavaFormatterXml() {} diff --git a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/XmlUtils.java b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/XmlUtils.java index 7225f7414..1a1114ffb 100644 --- a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/XmlUtils.java +++ b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/XmlUtils.java @@ -16,41 +16,250 @@ package com.palantir.javaformat.gradle; -import com.google.common.io.Files; -import groovy.util.Node; -import groovy.xml.XmlNodePrinter; -import groovy.xml.XmlParser; -import java.io.BufferedWriter; +import static java.nio.charset.StandardCharsets.UTF_8; + +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; -import java.io.PrintWriter; -import java.nio.charset.Charset; -import java.util.Map; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; import java.util.function.Consumer; +import java.util.stream.IntStream; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import org.w3c.dom.CDATASection; +import org.w3c.dom.Comment; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.ProcessingInstruction; +import org.w3c.dom.Text; +import org.xml.sax.Attributes; import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; +/** + * Edits the XML files in .idea with the JDK's DOM. The plugin does not declare Groovy, so Groovy's XmlParser would be + * whichever the build's Gradle bundles: Groovy 4 moved it out of groovy.util. + */ public class XmlUtils { - public static void updateIdeaXmlFile(File configurationFile, Consumer configure) { - Node rootNode; - if (configurationFile.isFile()) { - try { - rootNode = new XmlParser().parse(configurationFile); - } catch (IOException | SAXException | ParserConfigurationException e) { - throw new RuntimeException("Couldn't parse existing configuration file: " + configurationFile, e); + // .idea files have no DTD, and the parsers read none: Groovy's XmlParser did not either. + private static final String DISALLOW_DOCTYPE = "http://apache.org/xml/features/disallow-doctype-decl"; + + // The user data of an element that holds the names of its attributes, in the order of the file. + private static final String ATTRIBUTE_ORDER = "open-java-format.attributeOrder"; + + public static void updateIdeaXmlFile(File configurationFile, Consumer configure) { + if (!configurationFile.isFile()) { + var document = newDocumentBuilder().newDocument(); + var project = document.createElement("project"); + project.setAttribute("version", "4"); + document.appendChild(project); + configure.accept(project); + write(configurationFile, print(document)); + return; + } + + Document document; + try { + document = parse(Files.readAllBytes(configurationFile.toPath())); + } catch (IOException | SAXException e) { + throw new RuntimeException("Couldn't parse existing configuration file: " + configurationFile, e); + } + var before = print(document); + configure.accept(document.getDocumentElement()); + var after = print(document); + // A file with nothing to change keeps its bytes, however it was written. + if (!after.equals(before)) { + write(configurationFile, after); + } + } + + static Document parse(byte[] xml) throws IOException, SAXException { + var document = newDocumentBuilder().parse(new ByteArrayInputStream(xml)); + recordAttributeOrder(xml, document); + return document; + } + + /** + * The node as IntelliJ writes it: a file starts with the XML declaration and has no line break at the end, the + * elements are indented by two spaces, an empty one ends in {@code " />"}, and the attributes keep the order of the + * file. Text that is more than whitespace comes out as it is, and so does the rest of its element. + */ + static String print(Node node) { + var out = new StringBuilder(); + if (node instanceof Document document) { + out.append(""); + for (var child : children(document)) { + out.append('\n'); + print(child, "", out); } } else { - rootNode = new Node(null, "project", Map.of("version", "4")); + print(node, "", out); + } + return out.toString(); + } + + static List children(Node node) { + var children = node.getChildNodes(); + return IntStream.range(0, children.getLength()).mapToObj(children::item).toList(); + } + + // An element that holds elements alone puts each on a line of its own, in place of the whitespace between them. + private static void print(Node node, String indent, StringBuilder out) { + var children = children(node); + if (!(node instanceof Element element) || children.stream().anyMatch(XmlUtils::isText)) { + printInline(node, out); + return; + } + var nested = children.stream().filter(child -> !(child instanceof Text)).toList(); + printStartTag(element, out); + if (nested.isEmpty()) { + out.append(" />"); + return; + } + out.append('>'); + for (var child : nested) { + out.append('\n').append(indent).append(" "); + print(child, indent + " ", out); + } + out.append('\n') + .append(indent) + .append("'); + } + + private static void printInline(Node node, StringBuilder out) { + switch (node) { + case Element element -> { + printStartTag(element, out); + var children = children(element); + if (children.isEmpty()) { + out.append(" />"); + } else { + out.append('>'); + for (var child : children) { + printInline(child, out); + } + out.append("'); + } + } + case CDATASection cdata -> + out.append(""); + case Text text -> out.append(escape(text.getData(), false)); + case Comment comment -> out.append(""); + case ProcessingInstruction instruction -> { + out.append(""); + } + default -> throw new IllegalArgumentException("Unexpected XML node: " + node); + } + } + + private static void printStartTag(Element element, StringBuilder out) { + out.append('<').append(element.getTagName()); + for (var name : attributeNames(element)) { + out.append(' ') + .append(name) + .append("=\"") + .append(escape(element.getAttribute(name), true)) + .append('"'); } + } + + private static boolean isText(Node node) { + return node instanceof Text text + && (text instanceof CDATASection || !text.getData().isBlank()); + } - configure.accept(rootNode); + // Those the file had come in its order, then those added since, by name: the DOM keeps them sorted. + private static List attributeNames(Element element) { + var names = new ArrayList(); + if (element.getUserData(ATTRIBUTE_ORDER) instanceof String[] order) { + for (var name : order) { + if (element.hasAttribute(name)) { + names.add(name); + } + } + } + var attributes = element.getAttributes(); + for (var i = 0; i < attributes.getLength(); i++) { + var name = attributes.item(i).getNodeName(); + if (!names.contains(name)) { + names.add(name); + } + } + return names; + } + + // What IntelliJ escapes, and a carriage return besides. A line break or a tab in an attribute survives only as a + // character reference: a parser turns the characters themselves into spaces. + private static String escape(String value, boolean attribute) { + var out = new StringBuilder(value.length()); + for (var i = 0; i < value.length(); i++) { + var c = value.charAt(i); + switch (c) { + case '&' -> out.append("&"); + case '<' -> out.append("<"); + case '>' -> out.append(">"); + case '"' -> out.append("""); + case '\r' -> out.append(" "); + case '\n' -> out.append(attribute ? " " : "\n"); + case '\t' -> out.append(attribute ? " " : "\t"); + default -> out.append(c); + } + } + return out.toString(); + } + + // The DOM keeps an element's attributes sorted by name. SAX reads them in the order of the file, and meets the + // elements in the order getElementsByTagName returns them. + private static void recordAttributeOrder(byte[] xml, Document document) throws IOException, SAXException { + var elements = document.getElementsByTagName("*"); + try { + var factory = SAXParserFactory.newDefaultInstance(); + factory.setFeature(DISALLOW_DOCTYPE, true); + factory.newSAXParser().parse(new ByteArrayInputStream(xml), new DefaultHandler() { + private int next; + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) { + var order = new String[attributes.getLength()]; + for (var i = 0; i < order.length; i++) { + order[i] = attributes.getQName(i); + } + elements.item(next++).setUserData(ATTRIBUTE_ORDER, order, null); + } + }); + } catch (ParserConfigurationException e) { + throw new IllegalStateException(e); + } + } + + private static DocumentBuilder newDocumentBuilder() { + try { + var factory = DocumentBuilderFactory.newDefaultInstance(); + factory.setFeature(DISALLOW_DOCTYPE, true); + var builder = factory.newDocumentBuilder(); + // Throws on a fatal error, as the default does, without printing it to the console first. + builder.setErrorHandler(new DefaultHandler()); + return builder; + } catch (ParserConfigurationException e) { + throw new IllegalStateException(e); + } + } - try (BufferedWriter writer = Files.newWriter(configurationFile, Charset.defaultCharset()); - PrintWriter printWriter = new PrintWriter(writer)) { - XmlNodePrinter nodePrinter = new XmlNodePrinter(printWriter); - nodePrinter.setPreserveWhitespace(true); - nodePrinter.print(rootNode); + private static void write(File configurationFile, String xml) { + try { + Files.writeString(configurationFile.toPath(), xml, UTF_8); } catch (IOException e) { throw new RuntimeException("Failed to write back to configuration file: " + configurationFile, e); } diff --git a/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/ConfigureJavaFormatterXmlTest.java b/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/ConfigureJavaFormatterXmlTest.java index c20bafc7d..5b936da12 100644 --- a/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/ConfigureJavaFormatterXmlTest.java +++ b/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/ConfigureJavaFormatterXmlTest.java @@ -16,13 +16,10 @@ package com.palantir.javaformat.gradle; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import groovy.util.Node; -import groovy.xml.XmlNodePrinter; -import groovy.xml.XmlParser; -import java.io.PrintWriter; -import java.io.StringWriter; +import java.io.IOException; import java.net.URI; import java.util.List; import java.util.stream.Stream; @@ -31,6 +28,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; final class ConfigureJavaFormatterXmlTest { @@ -69,16 +68,15 @@ final class ConfigureJavaFormatterXmlTest { private static final String EXPECTED = """ - - - """; + """; static Stream actionsOnSave() { return Stream.of("Format", "Optimize"); @@ -86,7 +84,7 @@ static Stream actionsOnSave() { @Test void configure_missingEntireBlock_added() { - Node node = parseXml(MISSING_ENTIRE_BLOCK); + var node = parseXml(MISSING_ENTIRE_BLOCK); ConfigureJavaFormatterXml.configureJavaFormat(node, List.of(URI.create("foo"), URI.create("bar"))); @@ -95,24 +93,23 @@ void configure_missingEntireBlock_added() { @Test void configure_missingClassPath_added() { - Node node = parseXml(MISSING_CLASS_PATH); + var node = parseXml(MISSING_CLASS_PATH); ConfigureJavaFormatterXml.configureJavaFormat(node, List.of(URI.create("foo"), URI.create("bar"))); String expected = """ - - - """; + """; assertThat(xmlToString(node)).isEqualTo(expected); } @@ -121,7 +118,7 @@ void configure_missingClassPath_added() { void configure_existingClassPath_modified_andTheNativeImageOfEarlierVersionsRemoved() { // Up to 21.0.1 the plugin wrote nativeImageClassPath for openjavaformat.native.formatter=true. The IDE plugin // switches the native binary on by a setting of its own now, and no longer reads it. - Node node = parseXml(EXISTING_CLASS_PATH); + var node = parseXml(EXISTING_CLASS_PATH); ConfigureJavaFormatterXml.configureJavaFormat(node, List.of(URI.create("foo"), URI.create("bar"))); @@ -130,7 +127,7 @@ void configure_existingClassPath_modified_andTheNativeImageOfEarlierVersionsRemo @Test void configure_leavesTheIdePluginsNativeBinarySettingsAlone() { - Node node = parseXml(""" + var node = parseXml("""