-
Notifications
You must be signed in to change notification settings - Fork 153
/
PomTransformer.java
347 lines (307 loc) · 13.6 KB
/
PomTransformer.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package org.jfrog.build.extractor.maven.transformer;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jfrog.build.extractor.EolDetectingInputStream;
import org.jfrog.build.extractor.maven.reader.ModuleName;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Rewrites the project versions in the pom.
*
* @author Yossi Shaul
*/
public class PomTransformer {
private final String UNIX_DEFAULT_PARENT_POM_RELATIVE_PATH = "../pom.xml";
private final String WINDOWS_DEFAULT_PARENT_POM_RELATIVE_PATH = "..\\pom.xml";
private final String scmUrl;
private final ModuleName currentModule;
private final Map<ModuleName, String> versionsByModule;
private final boolean failOnSnapshot;
private final boolean dryRun;
private boolean modified;
private File pomFile;
private Map<String, String> pomProperties = new HashMap<String, String>();
private String nextPomToLoad = null;
/**
* Transforms single pom file.
*
* @param currentModule The current module we work on
* @param versionsByModule Map of module names to module version
* @param scmUrl Scm url to use if scm element exists in the pom file
*/
public PomTransformer(ModuleName currentModule, Map<ModuleName, String> versionsByModule, String scmUrl) {
this(currentModule, versionsByModule, scmUrl, false, false);
}
/**
* Transforms single pom file.
*
* @param currentModule The current module we work on
* @param versionsByModule Map of module names to module version
* @param scmUrl Scm url to use if scm element exists in the pom file
* @param failOnSnapshot If true, fail with IllegalStateException if the pom contains snapshot version after the
* version changes
*/
public PomTransformer(ModuleName currentModule, Map<ModuleName, String> versionsByModule, String scmUrl,
boolean failOnSnapshot) {
this(currentModule, versionsByModule, scmUrl, failOnSnapshot, false);
}
/**
* Transforms single pom file.
*
* @param currentModule The current module we work on
* @param versionsByModule Map of module names to module version
* @param scmUrl Scm url to use if scm element exists in the pom file
* @param failOnSnapshot If true, fail with IllegalStateException if the pom contains snapshot version after the
* version changes
* @param dryRun If true, changes will not take effect.
*/
public PomTransformer(ModuleName currentModule, Map<ModuleName, String> versionsByModule, String scmUrl,
boolean failOnSnapshot, boolean dryRun) {
this.currentModule = currentModule;
this.versionsByModule = versionsByModule;
this.scmUrl = scmUrl;
this.failOnSnapshot = failOnSnapshot;
this.dryRun = dryRun;
}
/**
* Performs the transformation.
*
* @return True if the file was modified.
*/
public Boolean transform(File pomFile) throws IOException {
this.pomFile = pomFile;
if (!pomFile.exists()) {
throw new IllegalArgumentException("Couldn't find pom file: " + pomFile);
}
SAXBuilder saxBuilder = createSaxBuilder();
Document document;
EolDetectingInputStream eolDetectingStream = null;
InputStreamReader inputStreamReader = null;
try {
eolDetectingStream = new EolDetectingInputStream(new FileInputStream(pomFile));
inputStreamReader = new InputStreamReader(eolDetectingStream, "UTF-8");
document = saxBuilder.build(inputStreamReader);
} catch (JDOMException e) {
throw new IOException("Failed to parse pom: " + pomFile.getAbsolutePath(), e);
} finally {
IOUtils.closeQuietly(inputStreamReader);
IOUtils.closeQuietly(eolDetectingStream);
}
Element rootElement = document.getRootElement();
Namespace ns = rootElement.getNamespace();
getProperties(rootElement, ns);
changeParentVersion(rootElement, ns);
changeCurrentModuleVersion(rootElement, ns);
//changePropertiesVersion(rootElement, ns);
changeDependencyManagementVersions(rootElement, ns);
changeDependencyVersions(rootElement, ns);
if (scmUrl != null) {
changeScm(rootElement, ns);
}
if (modified && !dryRun) {
FileOutputStream fileOutputStream = new FileOutputStream(pomFile);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
try {
XMLOutputter outputter = new XMLOutputter();
String eol = eolDetectingStream.getEol();
if (!"".equals(eol)) {
Format format = outputter.getFormat();
format.setLineSeparator(eol);
format.setTextMode(Format.TextMode.PRESERVE);
outputter.setFormat(format);
}
outputter.output(document, outputStreamWriter);
} finally {
IOUtils.closeQuietly(outputStreamWriter);
IOUtils.closeQuietly(fileOutputStream);
}
}
return modified;
}
private void getProperties(Element root, Namespace ns) {
Element propertiesElement = root.getChild("properties", ns);
if (propertiesElement == null) {
return;
}
List<Element> children = propertiesElement.getChildren();
for (Element child : children) {
String key = child.getName();
if (pomProperties.get(key) == null) {
pomProperties.put(key, child.getText());
}
}
}
private void changeParentVersion(Element root, Namespace ns) {
Element parentElement = root.getChild("parent", ns);
if (parentElement == null) {
return;
}
// We might need to use the parent pom for getting properties
// If the file has parent but relativePath is not set we use the default parent location
Element relativePath = parentElement.getChild("relativePath", ns);
String relativeParentPath = relativePath == null ? ".." + java.io.File.separator + "pom.xml" : relativePath.getText();
nextPomToLoad = StringUtils.substringBeforeLast(pomFile.getAbsolutePath(), java.io.File.separator) + java.io.File.separator + relativeParentPath;
ModuleName parentName = extractModuleName(parentElement, ns);
if (versionsByModule.containsKey(parentName)) {
setVersion(parentElement, ns, versionsByModule.get(parentName));
}
verifyNonSnapshotVersion(parentName, parentElement, ns);
}
private void changeCurrentModuleVersion(Element rootElement, Namespace ns) {
setVersion(rootElement, ns, versionsByModule.get(currentModule));
verifyNonSnapshotVersion(currentModule, rootElement, ns);
}
private void changeDependencyManagementVersions(Element rootElement, Namespace ns) {
Element dependencyManagement = rootElement.getChild("dependencyManagement", ns);
if (dependencyManagement == null) {
return;
}
Element dependenciesElement = dependencyManagement.getChild("dependencies", ns);
if (dependenciesElement == null) {
return;
}
List<Element> dependencies = dependenciesElement.getChildren("dependency", ns);
for (Element dependency : dependencies) {
changeDependencyVersion(ns, dependency);
}
}
private void changeDependencyVersions(Element rootElement, Namespace ns) {
Element dependenciesElement = rootElement.getChild("dependencies", ns);
if (dependenciesElement == null) {
return;
}
List<Element> dependencies = dependenciesElement.getChildren("dependency", ns);
for (Element dependency : dependencies) {
changeDependencyVersion(ns, dependency);
}
}
private void changeDependencyVersion(Namespace ns, Element dependency) {
ModuleName moduleName = extractModuleName(dependency, ns);
if (versionsByModule.containsKey(moduleName)) {
setVersion(dependency, ns, versionsByModule.get(moduleName));
}
verifyNonSnapshotVersion(moduleName, dependency, ns);
}
private void changeScm(Element rootElement, Namespace ns) {
Element scm = rootElement.getChild("scm", ns);
if (scm == null) {
return;
}
Element connection = scm.getChild("connection", ns);
if (connection != null) {
connection.setText("scm:svn:" + scmUrl);
}
Element developerConnection = scm.getChild("developerConnection", ns);
if (developerConnection != null) {
developerConnection.setText("scm:svn:" + scmUrl);
}
Element url = scm.getChild("url", ns);
if (url != null) {
url.setText(scmUrl);
}
}
private void setVersion(Element element, Namespace ns, String version) {
Element versionElement = element.getChild("version", ns);
if (versionElement != null) {
String currentVersion = versionElement.getText();
if (!version.equals(currentVersion)) {
versionElement.setText(version);
modified = true;
}
}
}
private void verifyNonSnapshotVersion(ModuleName moduleName, Element element, Namespace ns) {
if (!failOnSnapshot) {
return;
}
Element versionElement = element.getChild("version", ns);
if (versionElement != null) {
String currentVersion = versionElement.getText();
if (currentVersion.endsWith("-SNAPSHOT") ||
(currentVersion.startsWith("${") && currentVersion.endsWith("}")) && evalExpression(currentVersion) != null && evalExpression(currentVersion).endsWith("-SNAPSHOT")) {
throw new SnapshotNotAllowedException(String.format("Snapshot detected in file '%s': %s:%s",
pomFile.getAbsolutePath(), moduleName, currentVersion));
}
}
}
// Search for expression value in the pom properties
// If not found, try to find the value up in the pom hierarchy, lazy loading
private String evalExpression(String expr) {
String expression = pomProperties.get(expr.substring(2, expr.lastIndexOf("}")));
if (expression != null) {
return expression;
}
if (loadNextProperties()) {
return evalExpression(expr);
}
return null;
}
// The nextPomToLoad point to the next pom hierarchy
// load the next pom in chain and his properties
private boolean loadNextProperties() {
if (nextPomToLoad == null) {
return false;
}
MavenXpp3Reader mavenReader = new MavenXpp3Reader();
try (FileReader reader = new FileReader(nextPomToLoad)) {
Model model = mavenReader.read(reader);
Properties properties = model.getProperties();
for (String key : properties.stringPropertyNames()) {
if (pomProperties.get(key) == null) {
pomProperties.put(key, properties.getProperty(key));
}
}
Parent parent = model.getParent();
if (parent != null) {
String relativePath = parent.getRelativePath();
if (File.separatorChar == '\\' && UNIX_DEFAULT_PARENT_POM_RELATIVE_PATH.equals(relativePath)) {
relativePath = WINDOWS_DEFAULT_PARENT_POM_RELATIVE_PATH;
}
nextPomToLoad = StringUtils.substringBeforeLast(nextPomToLoad, File.separator) + File.separator + relativePath;
} else {
nextPomToLoad = null;
}
} catch (Exception e) {
Logger.getLogger(PomTransformer.class.getName()).info("couldn't load pom file at: " + nextPomToLoad);
return false;
}
return true;
}
private ModuleName extractModuleName(Element element, Namespace ns) {
String groupId = element.getChildText("groupId", ns);
String artifactId = element.getChildText("artifactId", ns);
if (StringUtils.isBlank(groupId) || StringUtils.isBlank(artifactId)) {
throw new IllegalArgumentException("Couldn't extract module key from: " + element);
}
return new ModuleName(groupId, artifactId);
}
static SAXBuilder createSaxBuilder() {
SAXBuilder sb = new SAXBuilder();
// don't validate and don't load dtd
sb.setValidation(false);
sb.setFeature("http://xml.org/sax/features/validation", false);
sb.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
sb.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
return sb;
}
}