Skip to content

Commit

Permalink
Merge pull request #321 from gounthar/fix-remove-comments
Browse files Browse the repository at this point in the history
fix(jdk7): Remove comments associated with deleted properties in pom.xml
  • Loading branch information
jonesbusy authored Oct 12, 2024
2 parents 9c7e63d + 4200c43 commit 3f29beb
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
Expand All @@ -26,10 +28,7 @@
public class PomModifier {

private static final Logger LOG = LoggerFactory.getLogger(PomModifier.class);
private Document document;

// Base directory for file operations
private static final String BASE_DIR = System.getProperty("java.io.tmpdir");
private final Document document;

/**
* Constructor for PomModifier.
Expand All @@ -43,7 +42,7 @@ public PomModifier(String pomFilePath) {
// Validate the file path
Path path = Paths.get(pomFilePath).normalize().toAbsolutePath();
if (!Files.exists(path) || !Files.isRegularFile(path)) {
throw new IllegalArgumentException("Invalid file path: " + path.toString());
throw new IllegalArgumentException("Invalid file path: " + path);
}

File pomFile = path.toFile();
Expand Down Expand Up @@ -77,24 +76,53 @@ public void removeOffendingProperties() {
if (propertiesList.getLength() > 0) {
Node propertiesNode = propertiesList.item(0);
NodeList childNodes = propertiesNode.getChildNodes();
List<Node> nodesToRemove = new ArrayList<>();

for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String nodeName = node.getNodeName();
if (nodeName.equals("jenkins-test-harness.version") || nodeName.equals("java.level")) {
propertiesNode.removeChild(node);
// Add the offending property to the list
nodesToRemove.add(node);

// Add preceding comments to the list
int j = i - 1;
while (j >= 0) {
Node previousNode = childNodes.item(j);
if (previousNode.getNodeType() == Node.COMMENT_NODE
|| (previousNode.getNodeType() == Node.TEXT_NODE
&& previousNode
.getTextContent()
.trim()
.startsWith("<!--"))
|| previousNode
.getTextContent()
.replaceAll("\\s+", "")
.isEmpty()) {
nodesToRemove.add(previousNode);
j--;
} else {
break; // Stop if a non-comment node is encountered
}
}
}
}
}

// Remove collected nodes
for (Node nodeToRemove : nodesToRemove) {
propertiesNode.removeChild(nodeToRemove);
}
}
}

/**
* Updates the parent POM information.
*
* @param groupId the groupId to set
* @param groupId the groupId to set
* @param artifactId the artifactId to set
* @param version the version to set
* @param version the version to set
*/
public void updateParentPom(String groupId, String artifactId, String version) {
NodeList parentList = document.getElementsByTagName("parent");
Expand Down Expand Up @@ -170,9 +198,9 @@ public void updateJenkinsMinimalVersion(String version) {
/**
* Adds a BOM section to the POM file.
*
* @param groupId the groupId of the BOM
* @param groupId the groupId of the BOM
* @param artifactId the artifactId of the BOM
* @param version the version of the BOM
* @param version the version of the BOM
*/
public void addBom(String groupId, String artifactId, String version) {
NodeList dependencyManagementList = document.getElementsByTagName("dependencyManagement");
Expand Down Expand Up @@ -226,9 +254,6 @@ public void addBom(String groupId, String artifactId, String version) {
@SuppressFBWarnings("PATH_TRAVERSAL_IN")
public void savePom(String outputPath) {
try {
// Validate the output path
Path path = Paths.get(outputPath).normalize().toAbsolutePath();

TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
Transformer transformer = transformerFactory.newTransformer();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package io.jenkins.tools.pluginmodernizer.core.utils;

import static java.nio.file.Files.createTempFile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.*;

import java.io.File;
import java.io.IOException;
Expand All @@ -18,6 +17,9 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
* Test class for PomModifier.
*/
public class PomModifierTest {
private static final Logger logger = Logger.getLogger(PomModifierTest.class.getName());

Expand All @@ -37,13 +39,23 @@ public class PomModifierTest {
}
}

/**
* Sets up the test environment by copying the test POM file to a temporary file.
*
* @throws Exception if an error occurs during setup
*/
@BeforeEach
public void setUp() throws Exception {
Path tempFile = new File(OUTPUT_POM_PATH).toPath();
Files.copy(Path.of(TEST_POM_PATH), tempFile, StandardCopyOption.REPLACE_EXISTING);
logger.info("Setup completed, copied test POM to temporary file: " + tempFile.toString());
logger.info("Setup completed, copied test POM to temporary file: " + tempFile);
}

/**
* Tests the removeOffendingProperties method of PomModifier.
*
* @throws Exception if an error occurs during the test
*/
@Test
public void testRemoveOffendingProperties() throws Exception {
PomModifier pomModifier = new PomModifier(OUTPUT_POM_PATH);
Expand All @@ -57,14 +69,32 @@ public void testRemoveOffendingProperties() throws Exception {

Element propertiesElement =
(Element) doc.getElementsByTagName("properties").item(0);
assertTrue(propertiesElement.getElementsByTagName("java.level").getLength() == 0);
assertTrue(propertiesElement
assertEquals(
0,
propertiesElement.getElementsByTagName("java.level").getLength(),
"java.level property should be removed");
assertEquals(
0,
propertiesElement
.getElementsByTagName("jenkins-test-harness.version")
.getLength()
== 0);
logger.info("Offending properties removed successfully");
.getLength(),
"jenkins-test-harness.version property should be removed");

// Verify that comments associated with the removed properties are also removed
String pomContent = new String(Files.readAllBytes(Paths.get(OUTPUT_POM_PATH)));
assertFalse(
pomContent.contains("Java Level to use. Java 7 required when using core >= 1.612"),
"Comment for java.level should be removed");
assertFalse(
pomContent.contains("Jenkins Test Harness version you use to test the plugin."),
"Comment for jenkins-test-harness.version should be removed");
}

/**
* Tests the updateParentPom method of PomModifier.
*
* @throws Exception if an error occurs during the test
*/
@Test
public void testUpdateParentPom() throws Exception {
PomModifier pomModifier = new PomModifier(OUTPUT_POM_PATH);
Expand All @@ -87,6 +117,11 @@ public void testUpdateParentPom() throws Exception {
"4.80", parentElement.getElementsByTagName("version").item(0).getTextContent());
}

/**
* Tests the updateJenkinsMinimalVersion method of PomModifier.
*
* @throws Exception if an error occurs during the test
*/
@Test
public void testUpdateJenkinsMinimalVersion() throws Exception {
PomModifier pomModifier = new PomModifier(OUTPUT_POM_PATH);
Expand Down

0 comments on commit 3f29beb

Please sign in to comment.