Backtestsjsouprun-20261006-181938#953
Add method Elements.before(Node node)
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches add `Elements.before(Node)` and `after(Node)`, and both resolve the issue. They differ in what happens to the supplied node. Patch A follows jQuery's model. Each target except the last gets a deep clone, and the last target gets the original node, which is moved. The clones are all made before any insertion, so they don't capture earlier insertions into the node's own subtree. A test (`beforeNodeContainingMatches`) covers this case. Patch B clones for every target and leaves the original untouched. That matches the user's `outerHtml()` workaround, so it is also reasonable. However, B makes each clone lazily inside the loop. If the supplied node contains any of the matched elements, earlier insertions change the node before it is cloned again, and later copies include those earlier clones. B neither handles nor tests this. Placement: A puts the logic in `Nodes`, alongside the existing `Nodes.before(String)` and `after(String)`, and adds covariant overrides in `Elements`. This follows the existing class split and also gives the feature to `Nodes<TextNode>` and similar collections. B adds the methods only to `Elements`. Tests: A's are stronger. They cover identity of the original versus the clones, a single-element chain, the self-containing case, and the `Nodes` variants. B tests output and that the original keeps a null parent. Scope: B also adds `prepend(Node)` and `append(Node)`. That is beyond the ask, so it is neutral. B also removes the `Iterator` and `Predicate` imports from `Elements.java`. That is unrelated churn, and if either import is still used it breaks compilation. Overall, A is more complete, better structured, better tested and lower risk.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
7m 44s
Wall-clock time in the container
Full test suite
No new failures
2,174 passed · 0 skipped · 2,174 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
131vs 90 merged
Changed lines, ours vs merged
The issue
View on GitHubHello,
We can made Element.before(Node node), Element.before(String html) and Elements.before(String html) .
Is it possible to add Elements.before(Node node) ?
Actually, I need to do myElements.before(myElement.outerHtml()) which isn't really pretty...
Regards,
Anael
The two patches
CHANGES.mdindex 117558e1..40ee0dca 100644@@ -9,6 +9,7 @@ * Improved `W3CDom` XML conversion to retain processing instructions, comments outside the root element, and CDATA sections, which were previously dropped or converted to text. [#2572](https://github.com/jhy/jsoup/issues/2572) * DOM mutation methods, including child insertion and replacement, now reject operations that would create a cycle, such as making a node its own child or moving an ancestor beneath a descendant. [#2552](https://github.com/jhy/jsoup/issues/2552) * XML serialization now repairs element and attribute names that start with an invalid character, rather than outputting `<null>` elements or dropping attributes. For example, an attribute named `1a` is written as `_1a`. Additional leading underscores keep repaired attribute names unique if they conflict with another attribute. [#2573](https://github.com/jhy/jsoup/issues/2573)+* Added `Elements.before(Node)` and `Elements.after(Node)` (and the same on `Nodes`), to insert a node before or after each matched element. Each matched element except the last receives a deep clone of the node; the last receives the original. ### Changes * Aligned the XML parser stack depth and lookups to the configured maximum, which now defaults to 512 for both HTML and XML. [#2570](https://github.com/jhy/jsoup/pull/2570)src/main/java/org/jsoup/select/Elements.javaindex e84e2a0e..a54ae4d7 100644@@ -341,6 +341,21 @@ public class Elements extends Nodes<Element> { return this; } + /**+ Insert the supplied node before each matched element's outer HTML. If there is more than one matched element, a+ deep clone of the node is inserted before each element except the last, which receives the original node.++ @param node node to insert before each element+ @return this, for chaining+ @see Element#before(Node)+ @since 1.23.2+ */+ @Override+ public Elements before(Node node) {+ super.before(node);+ return this;+ }+ /** Insert the supplied HTML after each matched element's outer HTML. @@ -354,6 +369,21 @@ public class Elements extends Nodes<Element> { return this; } + /**+ Insert the supplied node after each matched element's outer HTML. If there is more than one matched element, a+ deep clone of the node is inserted after each element except the last, which receives the original node.++ @param node node to insert after each element+ @return this, for chaining+ @see Element#after(Node)+ @since 1.23.2+ */+ @Override+ public Elements after(Node node) {+ super.after(node);+ return this;+ }+ /** Wrap the supplied HTML around each matched elements. For example, with HTML {@code <p><b>This</b> is <b>Jsoup</b></p>},src/main/java/org/jsoup/select/Nodes.javaindex 35fca117..284689b8 100644@@ -135,6 +135,26 @@ public class Nodes<T extends Node> extends ArrayList<T> { return this; } + /**+ Insert the supplied node before each matched node's outer HTML.+ <p>A node can only exist in one place in the DOM, so if there is more than one matched node, a deep clone of the+ supplied node is inserted before each matched node except the last, which receives the original node (which is+ moved from its current location, if it has one).</p>++ @param node node to insert before each matched node+ @return this, for chaining+ @see Node#before(Node)+ @since 1.23.2+ */+ public Nodes<T> before(Node node) {+ Validate.notNull(node);+ Node[] inserts = insertsOf(node);+ for (int i = 0; i < inserts.length; i++) {+ get(i).before(inserts[i]);+ }+ return this;+ }+ /** Insert the supplied HTML after each matched nodes's outer HTML. @@ -149,6 +169,36 @@ public class Nodes<T extends Node> extends ArrayList<T> { return this; } + /**+ Insert the supplied node after each matched node's outer HTML.+ <p>A node can only exist in one place in the DOM, so if there is more than one matched node, a deep clone of the+ supplied node is inserted after each matched node except the last, which receives the original node (which is+ moved from its current location, if it has one).</p>++ @param node node to insert after each matched node+ @return this, for chaining+ @see Node#after(Node)+ @since 1.23.2+ */+ public Nodes<T> after(Node node) {+ Validate.notNull(node);+ Node[] inserts = insertsOf(node);+ for (int i = 0; i < inserts.length; i++) {+ get(i).after(inserts[i]);+ }+ return this;+ }++ /** Clones of the node for each but the last matched node (which gets the original). Clones are made up front, so+ that they are not affected by earlier insertions into the node's subtree. */+ private Node[] insertsOf(Node node) {+ int size = size();+ Node[] inserts = new Node[size];+ for (int i = 0; i < size - 1; i++) inserts[i] = node.clone();+ if (size > 0) inserts[size - 1] = node;+ return inserts;+ }+ /** Wrap the supplied HTML around each matched node. For example, with HTML {@code <p><b>This</b> is <b>Jsoup</b></p>},src/test/java/org/jsoup/select/ElementsTest.javaindex b1b9b3dd..afc30ec5 100644@@ -175,6 +175,41 @@ public class ElementsTest { assertEquals("<p>This <a>is</a><span>foo</span> <a>jsoup</a><span>foo</span>.</p>", TextUtil.stripNewlines(doc.body().html())); } + @Test public void beforeNode() {+ Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p><div><span id=s>foo</span></div>");+ Element span = doc.expectFirst("#s");+ Elements as = doc.select("a");+ assertSame(as, as.before(span));+ assertEquals("<p>This <span id=\"s\">foo</span><a>is</a> <span id=\"s\">foo</span><a>jsoup</a>.</p><div></div>", TextUtil.stripNewlines(doc.body().html()));+ assertSame(span, as.last().previousSibling()); // original moved to the last target; others get clones+ assertNotSame(span, as.first().previousSibling());+ }++ @Test public void afterNode() {+ Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>");+ Element span = new Element("span").text("foo");+ Elements as = doc.select("a");+ assertSame(as, as.after(span));+ assertEquals("<p>This <a>is</a><span>foo</span> <a>jsoup</a><span>foo</span>.</p>", TextUtil.stripNewlines(doc.body().html()));+ assertSame(span, as.last().nextSibling());+ assertNotSame(span, as.first().nextSibling());+ }++ @Test public void beforeNodeContainingMatches() {+ // clones are taken before any insertion, so each is a copy of the node as originally supplied+ Document doc = Jsoup.parse("<div id=d><a>1</a><a>2</a></div><a>3</a>");+ Element div = doc.expectFirst("#d");+ doc.select("a").before(div);+ assertEquals("<div id=\"d\"><div id=\"d\"><a>1</a><a>2</a></div><a>1</a><div id=\"d\"><a>1</a><a>2</a></div><a>2</a></div><a>3</a>",+ TextUtil.stripNewlines(doc.body().html()));+ }++ @Test public void beforeAfterNodeSingle() {+ Document doc = Jsoup.parse("<p><a>One</a></p>");+ doc.select("a").before(new TextNode("x")).after(new TextNode("y"));+ assertEquals("<p>x<a>One</a>y</p>", doc.body().html());+ }+ @Test public void wrap() { String h = "<p><b>This</b> is <b>jsoup</b></p>"; Document doc = Jsoup.parse(h);src/test/java/org/jsoup/select/NodesTest.javaindex 411e1b26..00f70744 100644@@ -2,6 +2,7 @@ package org.jsoup.select; import org.jsoup.Jsoup; import org.jsoup.nodes.Document;+import org.jsoup.nodes.Element; import org.jsoup.nodes.TextNode; import org.junit.jupiter.api.Test; @@ -22,6 +23,20 @@ public class NodesTest { assertEquals("<span>One<wbr></span> <span>Two<wbr></span> <span>Three</span>", doc.body().html()); } + @Test void beforeNode() {+ Document doc = Jsoup.parse("<span>One</span> <span>Two</span> <span>Three</span>");+ Nodes<TextNode> nodes = doc.selectNodes("::text:contains(o)", TextNode.class);+ nodes.before(new Element("wbr"));+ assertEquals("<span><wbr>One</span> <span><wbr>Two</span> <span>Three</span>", doc.body().html());+ }++ @Test void afterNode() {+ Document doc = Jsoup.parse("<span>One</span> <span>Two</span> <span>Three</span>");+ Nodes<TextNode> nodes = doc.selectNodes("::text:contains(o)", TextNode.class);+ nodes.after(new Element("wbr"));+ assertEquals("<span>One<wbr></span> <span>Two<wbr></span> <span>Three</span>", doc.body().html());+ }+ @Test void wrap() { Document doc = Jsoup.parse("<span>One</span> <span>Two</span> <span>Three</span>"); Nodes<TextNode> nodes = doc.selectNodes("::text:contains(o)", TextNode.class);
CHANGES.mdindex 117558e1..30caabdf 100644@@ -8,6 +8,7 @@ * Improved `W3CDom` conversion performance for documents with many nested namespace declarations. The W3C converter now uses the same optimized namespace tracking as the XML parser. [#2559](https://github.com/jhy/jsoup/pull/2559) * Improved `W3CDom` XML conversion to retain processing instructions, comments outside the root element, and CDATA sections, which were previously dropped or converted to text. [#2572](https://github.com/jhy/jsoup/issues/2572) * DOM mutation methods, including child insertion and replacement, now reject operations that would create a cycle, such as making a node its own child or moving an ancestor beneath a descendant. [#2552](https://github.com/jhy/jsoup/issues/2552)+* Added `Elements#before(Node)`, `after(Node)`, `prepend(Node)`, and `append(Node)` to match the existing HTML string methods. [#953](https://github.com/jhy/jsoup/issues/953) * XML serialization now repairs element and attribute names that start with an invalid character, rather than outputting `<null>` elements or dropping attributes. For example, an attribute named `1a` is written as `_1a`. Additional leading underscores keep repaired attribute names unique if they conflict with another attribute. [#2573](https://github.com/jhy/jsoup/issues/2573) ### Changessrc/main/java/org/jsoup/select/Elements.javaindex e84e2a0e..aaca336f 100644@@ -14,10 +14,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet;-import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List;-import java.util.function.Predicate;+import java.util.function.BiConsumer; import java.util.function.UnaryOperator; /**@@ -314,6 +313,17 @@ public class Elements extends Nodes<Element> { } return this; }++ /**+ Add the supplied node to the start of each matched element's inner HTML. The node is cloned for each target.++ @param node the node to add inside each element, before the existing HTML+ @return this, for chaining+ @see Element#prependChild(Node)+ */+ public Elements prepend(Node node) {+ return insert(node, Element::prependChild);+ } /** * Add the supplied HTML to the end of each matched element's inner HTML.@@ -328,6 +338,17 @@ public class Elements extends Nodes<Element> { return this; } + /**+ Add the supplied node to the end of each matched element's inner HTML. The node is cloned for each target.++ @param node the node to add inside each element, after the existing HTML+ @return this, for chaining+ @see Element#appendChild(Node)+ */+ public Elements append(Node node) {+ return insert(node, Element::appendChild);+ }+ /** Insert the supplied HTML before each matched element's outer HTML. @@ -341,6 +362,17 @@ public class Elements extends Nodes<Element> { return this; } + /**+ Insert the supplied node before each matched element's outer HTML. The node is cloned for each target.++ @param node the node to insert before each element+ @return this, for chaining+ @see Element#before(Node)+ */+ public Elements before(Node node) {+ return insert(node, Element::before);+ }+ /** Insert the supplied HTML after each matched element's outer HTML. @@ -354,6 +386,31 @@ public class Elements extends Nodes<Element> { return this; } + /**+ Insert the supplied node after each matched element's outer HTML. The node is cloned for each target.++ @param node the node to insert after each element+ @return this, for chaining+ @see Element#after(Node)+ */+ public Elements after(Node node) {+ return insert(node, Element::after);+ }++ /**+ Applies a node insertion to each matched element, cloning the node for each target.++ @param node the node to insert+ @param inserter the insertion operation+ @return this, for chaining+ */+ private Elements insert(Node node, BiConsumer<Element, Node> inserter) {+ Validate.notNull(node);+ for (Element element : this)+ inserter.accept(element, node.clone());+ return this;+ }+ /** Wrap the supplied HTML around each matched elements. For example, with HTML {@code <p><b>This</b> is <b>Jsoup</b></p>},src/test/java/org/jsoup/select/ElementsTest.javaindex b1b9b3dd..2a39215d 100644@@ -169,12 +169,40 @@ public class ElementsTest { assertEquals("<p>This <span>foo</span><a>is</a> <span>foo</span><a>jsoup</a>.</p>", TextUtil.stripNewlines(doc.body().html())); } + @Test public void beforeNode() {+ Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>");+ Element span = new Element("span").text("foo");+ doc.select("a").before(span);+ assertEquals("<p>This <span>foo</span><a>is</a> <span>foo</span><a>jsoup</a>.</p>", TextUtil.stripNewlines(doc.body().html()));+ assertNull(span.parent()); // cloned per target; original is left alone+ assertNotSame(span, doc.selectFirst("span"));+ }+ @Test public void after() { Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>"); doc.select("a").after("<span>foo</span>"); assertEquals("<p>This <a>is</a><span>foo</span> <a>jsoup</a><span>foo</span>.</p>", TextUtil.stripNewlines(doc.body().html())); } + @Test public void afterNode() {+ Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>");+ Element span = new Element("span").text("foo");+ doc.select("a").after(span);+ assertEquals("<p>This <a>is</a><span>foo</span> <a>jsoup</a><span>foo</span>.</p>", TextUtil.stripNewlines(doc.body().html()));+ assertNull(span.parent());+ }++ @Test public void prependAppendNode() {+ Document doc = Jsoup.parse("<p>One</p><p>Two</p><p>Three</p>");+ Elements ps = doc.select("p");+ Element bold = new Element("b").text("Bold");+ Element ital = new Element("i").text("Ital");+ ps.prepend(bold).append(ital);+ assertEquals("<p><b>Bold</b>Two<i>Ital</i></p>", TextUtil.stripNewlines(ps.get(1).outerHtml()));+ assertNull(bold.parent());+ assertNull(ital.parent());+ }+ @Test public void wrap() { String h = "<p><b>This</b> is <b>jsoup</b></p>"; Document doc = Jsoup.parse(h);