/
KeepCommentsInPom.java
269 lines (252 loc) · 9.43 KB
/
KeepCommentsInPom.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package org.codehaus.mojo.flatten;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.SAXException;
/**
* Helper class to keep the comments how they have been in the original pom.xml While reading with
* {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} the comments are not placed into the
* {@link org.apache.maven.model.Model} and so {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} is not able to
* re-write those comments.
*
* Workaround (maybe until core is fixed) is to remember all the comments and restore them after MavenXpp3Writer has
* created the new flattened pom.xml.
*
* Current restriction on non-unique child nodes is that this class finds the node back due to the position in the file,
* that may lead to mis-re-added comments e.g. on multiple added dependencies (but for e.g. resolveCiFriendliesOnly the
* nodes keep stable)
*
*/
class KeepCommentsInPom
{
/**
* Create an instance with collected current comments of the passed pom.xml file.
*/
static KeepCommentsInPom create(Log aLog, File aOriginalPomFile) throws MojoExecutionException
{
KeepCommentsInPom tempKeepCommentsInPom = new KeepCommentsInPom();
tempKeepCommentsInPom.setLog(aLog);
tempKeepCommentsInPom.loadComments(aOriginalPomFile);
return tempKeepCommentsInPom;
}
private Log log;
/**
* The unique path list for an original node (the comments are stored via the referenced previousSibling)
*/
private Map<String, Node> commentsPaths;
/**
*
*/
KeepCommentsInPom()
{
super();
}
/**
* load all current comments and text fragments from xml file
*
* @param anOriginalPomFile the pom.xml
*/
private void loadComments(File anOriginalPomFile) throws MojoExecutionException
{
commentsPaths = new HashMap<>();
DocumentBuilderFactory tempDBF = DocumentBuilderFactory.newInstance();
DocumentBuilder tempDB;
try
{
tempDB = tempDBF.newDocumentBuilder();
Document tempPom = tempDB.parse(anOriginalPomFile);
Node tempNode = tempPom.getDocumentElement();
walkOverNodes(tempNode, ".", (node, nodePath) ->
{
// collectNodesByPathNames
commentsPaths.put(nodePath, node);
});
} catch (ParserConfigurationException | SAXException | IOException e)
{
throw new MojoExecutionException("Cannot load comments from " + anOriginalPomFile, e);
}
}
/**
* Walk over the pom hierarchy of the Document.
*
* @param Node the current Node
* @param String the unique path in the parent
* @param aConsumer Function to be called with the toBeCollected/found node.
*/
private void walkOverNodes(Node aNode, String aParentPath, BiConsumer<Node, String> aConsumer)
{
String tempNodeName = aNode.getNodeName();
if (log.isDebugEnabled())
{
log.debug("walkOverNodes: aParentPath=" + aParentPath + " tempNodeName=" + tempNodeName);
}
String tempNodePath = aParentPath + "\t" + tempNodeName;
aConsumer.accept(aNode, tempNodePath);
NodeList tempChilds = aNode.getChildNodes();
// Copy the childs as aConsumer may change the node sequence (add a comment)
List<Node> tempCopiedChilds = new ArrayList<>();
Map<String, Integer> tempChildWithSameName = new HashMap<>();
for (int i = 0; i < tempChilds.getLength(); i++)
{
Node tempItem = tempChilds.item(i);
if (tempItem.getNodeType() != Node.TEXT_NODE && tempItem.getNodeType() != Node.COMMENT_NODE)
{
// Take real nodes to find them back by number
String tempChildNodeName = tempItem.getNodeName();
Integer tempChildWithSameNameCount = tempChildWithSameName.get(tempChildNodeName);
if (tempChildWithSameNameCount == null)
{
tempChildWithSameNameCount = 1;
} else
{
tempChildWithSameNameCount += 1;
}
tempChildWithSameName.put(tempChildNodeName, tempChildWithSameNameCount);
tempCopiedChilds.add(tempItem);
}
}
Map<String, Integer> tempChildWithSameNameCounters = new HashMap<>();
for (int i = 0; i < tempCopiedChilds.size(); i++)
{
Node tempCopiedChild = tempCopiedChilds.get(i);
String tempChildNodeName = tempCopiedChild.getNodeName();
if (tempChildWithSameName.get(tempChildNodeName) > 1)
{
Integer tempChildWithSameNameCounter = tempChildWithSameNameCounters.get(tempChildNodeName);
if (tempChildWithSameNameCounter == null)
{
tempChildWithSameNameCounter = 1;
} else
{
tempChildWithSameNameCounter += 1;
}
tempChildWithSameNameCounters.put(tempChildNodeName, tempChildWithSameNameCounter);
// add a counter to find back the correct node.
walkOverNodes(tempCopiedChild, tempNodePath + "\t" + tempChildWithSameNameCounter, aConsumer);
} else
{
// unique child names
walkOverNodes(tempCopiedChild, tempNodePath, aConsumer);
}
}
}
/**
* @param String the XML written by {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer}
*/
public String restoreOriginalComments(String anXml, String aModelEncoding) throws MojoExecutionException
{
DocumentBuilderFactory tempDBF = DocumentBuilderFactory.newInstance();
DocumentBuilder tempDB;
try
{
tempDB = tempDBF.newDocumentBuilder();
String tempEncoding = aModelEncoding == null ? "UTF-8" : aModelEncoding; // default encoding UTF-8 when
// nothing in pom model.
Document tempPom = tempDB.parse(new ByteArrayInputStream(anXml.getBytes(tempEncoding)));
Node tempNode = tempPom.getDocumentElement();
walkOverNodes(tempNode, ".", (newNode, nodePath) ->
{
Node tempOriginalNode = commentsPaths.get(nodePath);
if (tempOriginalNode != null)
{
String tempOriginalNodeName = tempOriginalNode.getNodeName();
if (tempOriginalNodeName.equals(newNode.getNodeName()))
{
// found matching node
Node tempRefChild = newNode;
Node tempPotentialCommentOrText = tempOriginalNode.getPreviousSibling();
while (tempPotentialCommentOrText != null
&& tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE)
{
// skip text in the original xml node
tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling();
}
while (tempPotentialCommentOrText != null
&& tempPotentialCommentOrText.getNodeType() == Node.COMMENT_NODE)
{
// copy the node to be able to call previoussibling for next element
Node tempRefPrevious = tempRefChild.getPreviousSibling();
String tempWhitespaceTextBeforeRefNode = null;
if (tempRefPrevious != null && tempRefPrevious.getNodeType() == Node.TEXT_NODE)
{
tempWhitespaceTextBeforeRefNode = tempRefPrevious.getNodeValue();
}
Node tempNewComment;
tempNewComment = tempPom.createComment(tempPotentialCommentOrText.getNodeValue());
tempRefChild.getParentNode().insertBefore(tempNewComment, tempRefChild);
// copy the whitespaces between comment and refNode
if (tempWhitespaceTextBeforeRefNode != null)
{
tempRefChild.getParentNode().insertBefore(
tempPom.createTextNode(tempWhitespaceTextBeforeRefNode), tempRefChild);
}
tempRefChild = tempNewComment;
tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling();
while (tempPotentialCommentOrText != null
&& tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE)
{
// skip text in the original xml node
tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling();
}
}
}
}
});
return writeDocumentToString(tempPom);
} catch (ParserConfigurationException | SAXException | IOException | ClassNotFoundException
| InstantiationException | IllegalAccessException | ClassCastException e)
{
throw new MojoExecutionException("Cannot add comments", e);
}
}
/**
* Use an LSSerializer to keep whitespaces added by MavenXpp3Writer
*
* @param Document the pom to write to String.
*/
private String writeDocumentToString(Document aPom)
throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSOutput output = impl.createLSOutput();
output.setEncoding("UTF-8");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
output.setByteStream(outStream);
LSSerializer writer = impl.createLSSerializer();
writer.write(aPom, output);
return new String(outStream.toByteArray());
}
/**
* @see #log
*/
public Log getLog()
{
return log;
}
/**
* @see #log
*/
public void setLog(Log aLog)
{
log = aLog;
}
}