-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathJGitverModelProcessor.java
More file actions
405 lines (344 loc) · 14.3 KB
/
Copy pathJGitverModelProcessor.java
File metadata and controls
405 lines (344 loc) · 14.3 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
* Copyright (C) 2016 Matthieu Brouillard [http://oss.brouillard.fr/jgitver-maven-plugin] (matthieu@brouillard.fr)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.brouillard.oss.jgitver;
import fr.brouillard.oss.jgitver.metadata.Metadatas;
import fr.brouillard.oss.jgitver.mojos.JGitverAttachModifiedPomsMojo;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.function.Predicate;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.building.Source;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Build;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.model.Scm;
import org.apache.maven.model.building.DefaultModelProcessor;
import org.apache.maven.model.building.ModelProcessor;
import org.apache.maven.plugin.LegacySupport;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.util.xml.Xpp3Dom;
;
/** Replacement ModelProcessor using jgitver while loading POMs in order to adapt versions. */
@Singleton
@Named
public class JGitverModelProcessor extends DefaultModelProcessor {
public static final String FLATTEN_MAVEN_PLUGIN = "flatten-maven-plugin";
public static final String ORG_CODEHAUS_MOJO = "org.codehaus.mojo";
@Inject private Logger logger = null;
@Inject private LegacySupport legacySupport = null;
@Inject private JGitverConfiguration configurationProvider;
@Inject private JGitverSessionHolder jgitverSession;
public JGitverModelProcessor() {
super();
}
@Override
public Model read(File input, Map<String, ?> options) throws IOException {
return provisionModel(super.read(input, options), options);
}
@Override
public Model read(Reader input, Map<String, ?> options) throws IOException {
return provisionModel(super.read(input, options), options);
}
@Override
public Model read(InputStream input, Map<String, ?> options) throws IOException {
return provisionModel(super.read(input, options), options);
}
private Model provisionModel(Model model, Map<String, ?> options) throws IOException {
MavenSession session = legacySupport.getSession();
Optional<JGitverSession> optSession = jgitverSession.session();
if (!optSession.isPresent()) {
// don't do anything in case no jgitver is there (execution could have been skipped)
return model;
} else {
Source source = (Source) options.get(ModelProcessor.SOURCE);
if (source == null) {
return model;
}
File location = new File(source.getLocation());
if (!location.isFile()) {
// their JavaDoc says Source.getLocation "could be a local file path, a URI or just an empty
// string."
// if it doesn't resolve to a file then calling .getParentFile will throw an exception,
// but if it doesn't resolve to a file then it isn't under getMultiModuleProjectDirectory,
return model; // therefore the model shouldn't be modified.
}
if (configurationProvider.ignore(location)) {
logger.debug("file " + location + " ignored by configuration");
return model;
}
JGitverSession jgitverSession = optSession.get();
File relativePath = location.getParentFile().getCanonicalFile();
File multiModuleDirectory = jgitverSession.getMultiModuleDirectory();
String calculatedVersion = jgitverSession.getVersion();
if (StringUtils.containsIgnoreCase(
relativePath.getCanonicalPath(), multiModuleDirectory.getCanonicalPath())) {
logger.debug("handling version of project Model from " + location);
jgitverSession.addProject(GAV.from(model.clone()));
if (Objects.nonNull(model.getVersion())) {
// TODO evaluate how to set the version only when it was originally set in the pom file
model.setVersion(calculatedVersion);
}
if (Objects.nonNull(model.getParent())) {
// if the parent is part of the multi module project, let's update the parent version
String modelParentRelativePath = model.getParent().getRelativePath();
File relativePathParent =
new File(relativePath.getCanonicalPath() + File.separator + modelParentRelativePath)
.getParentFile()
.getCanonicalFile();
if (StringUtils.isNotBlank(modelParentRelativePath)
&& StringUtils.containsIgnoreCase(
relativePathParent.getCanonicalPath(), multiModuleDirectory.getCanonicalPath())) {
model.getParent().setVersion(calculatedVersion);
}
}
// we should only register the plugin once, on the main project
if (relativePath.getCanonicalPath().equals(multiModuleDirectory.getCanonicalPath())) {
if (JGitverUtils.shouldUseFlattenPlugin(session)) {
if (shouldSkipPomUpdate(model)) {
logger.info(
"skipPomUpdate property is activated, jgitver will not define any maven-flatten-plugin execution");
} else {
if (isFlattenPluginDirectlyUsed(model)) {
logger.info(
"maven-flatten-plugin detected, jgitver will not define it's own execution");
} else {
logger.info("adding maven-flatten-plugin execution with jgitver defaults");
addFlattenPlugin(model);
}
}
} else {
addAttachPomMojo(model);
}
updateScmTag(jgitverSession.getCalculator(), model);
}
try {
session
.getUserProperties()
.put(
JGitverUtils.SESSION_MAVEN_PROPERTIES_KEY,
JGitverSession.serializeTo(jgitverSession));
} catch (Exception ex) {
throw new IOException("cannot serialize JGitverSession", ex);
}
} else {
logger.debug("skipping Model from " + location);
}
}
return model;
}
private void addFlattenPlugin(Model model) {
ensureBuildWithPluginsExistInModel(model);
Plugin flattenPlugin = new Plugin();
flattenPlugin.setGroupId(ORG_CODEHAUS_MOJO);
flattenPlugin.setArtifactId(FLATTEN_MAVEN_PLUGIN);
flattenPlugin.setVersion(System.getProperty("jgitver.flatten.version", "1.0.1"));
PluginExecution flattenPluginExecution = new PluginExecution();
flattenPluginExecution.setId("jgitver-flatten-pom");
flattenPluginExecution.addGoal("flatten");
flattenPluginExecution.setPhase(
System.getProperty("jgitver.pom-replacement-phase", "validate"));
flattenPlugin.getExecutions().add(flattenPluginExecution);
Xpp3Dom executionConfiguration = buildFlattenPluginConfiguration();
flattenPluginExecution.setConfiguration(executionConfiguration);
model.getBuild().getPlugins().add(flattenPlugin);
}
private void ensureBuildWithPluginsExistInModel(Model model) {
if (Objects.isNull(model.getBuild())) {
model.setBuild(new Build());
}
if (Objects.isNull(model.getBuild().getPlugins())) {
model.getBuild().setPlugins(new ArrayList<>());
}
}
private Xpp3Dom buildFlattenPluginConfiguration() {
Xpp3Dom configuration = new Xpp3Dom("configuration");
Xpp3Dom flattenMode = new Xpp3Dom("flattenMode");
flattenMode.setValue("defaults");
Xpp3Dom updatePomFile = new Xpp3Dom("updatePomFile");
updatePomFile.setValue("true");
Xpp3Dom pomElements = new Xpp3Dom("pomElements");
Xpp3Dom dependencyManagement = new Xpp3Dom("dependencyManagement");
dependencyManagement.setValue("keep");
pomElements.addChild(dependencyManagement);
List<String> pomElementsName =
Arrays.asList(
"build",
"ciManagement",
"contributors",
"dependencies",
"description",
"developers",
"distributionManagement",
"inceptionYear",
"issueManagement",
"mailingLists",
"modules",
"name",
"organization",
"parent",
"pluginManagement",
"pluginRepositories",
"prerequisites",
"profiles",
"properties",
"reporting",
"repositories",
"scm",
"url",
"version");
pomElementsName.forEach(
elementName -> {
Xpp3Dom node = new Xpp3Dom(elementName);
node.setValue("resolve");
pomElements.addChild(node);
});
configuration.addChild(flattenMode);
configuration.addChild(updatePomFile);
configuration.addChild(pomElements);
return configuration;
}
private boolean shouldSkipPomUpdate(Model model) throws IOException {
try {
return configurationProvider.getConfiguration().skipPomUpdate;
} catch (MavenExecutionException mee) {
throw new IOException("cannot load jgitver configuration", mee);
}
}
private boolean isFlattenPluginDirectlyUsed(Model model) {
Predicate<Plugin> isFlattenPlugin =
p ->
ORG_CODEHAUS_MOJO.equals(p.getGroupId())
&& FLATTEN_MAVEN_PLUGIN.equals(p.getArtifactId());
List<Plugin> pluginList =
Optional.ofNullable(model.getBuild())
.map(Build::getPlugins)
.orElse(Collections.emptyList());
return pluginList.stream().filter(isFlattenPlugin).findAny().isPresent();
}
private void updateScmTag(JGitverInformationProvider calculator, Model model) {
if (model.getScm() != null) {
Scm scm = model.getScm();
if (isVersionFromTag(calculator)) {
scm.setTag(calculator.getVersion());
} else {
calculator.meta(Metadatas.GIT_SHA1_FULL).ifPresent(scm::setTag);
}
}
}
private boolean isVersionFromTag(JGitverInformationProvider calculator) {
List<String> versionTagsOnHead =
Arrays.asList(calculator.meta(Metadatas.HEAD_VERSION_ANNOTATED_TAGS).orElse("").split(","));
String baseTag = calculator.meta(Metadatas.BASE_TAG).orElse("");
return versionTagsOnHead.contains(baseTag);
}
private void addAttachPomMojo(Model model) {
ensureBuildWithPluginsExistInModel(model);
Optional<Plugin> pluginOptional =
model.getBuild().getPlugins().stream()
.filter(
x ->
JGitverUtils.EXTENSION_GROUP_ID.equalsIgnoreCase(x.getGroupId())
&& JGitverUtils.EXTENSION_ARTIFACT_ID.equalsIgnoreCase(x.getArtifactId()))
.findFirst();
StringBuilder pluginVersion = new StringBuilder();
try (InputStream inputStream =
getClass()
.getResourceAsStream(
"/META-INF/maven/"
+ JGitverUtils.EXTENSION_GROUP_ID
+ "/"
+ JGitverUtils.EXTENSION_ARTIFACT_ID
+ "/pom"
+ ".properties")) {
Properties properties = new Properties();
properties.load(inputStream);
pluginVersion.append(properties.getProperty("version"));
} catch (IOException ignored) {
// TODO we should not ignore in case we have to reuse it
logger.warn(ignored.getMessage(), ignored);
}
Plugin plugin =
pluginOptional.orElseGet(
() -> {
Plugin plugin2 = new Plugin();
plugin2.setGroupId(JGitverUtils.EXTENSION_GROUP_ID);
plugin2.setArtifactId(JGitverUtils.EXTENSION_ARTIFACT_ID);
plugin2.setVersion(pluginVersion.toString());
model.getBuild().getPlugins().add(0, plugin2);
return plugin2;
});
if (Objects.isNull(plugin.getExecutions())) {
plugin.setExecutions(new ArrayList<>());
}
String pluginRunPhase = System.getProperty("jgitver.pom-replacement-phase", "prepare-package");
Optional<PluginExecution> pluginExecutionOptional =
plugin.getExecutions().stream()
.filter(x -> pluginRunPhase.equalsIgnoreCase(x.getPhase()))
.findFirst();
PluginExecution pluginExecution =
pluginExecutionOptional.orElseGet(
() -> {
PluginExecution pluginExecution2 = new PluginExecution();
pluginExecution2.setPhase(pluginRunPhase);
plugin.getExecutions().add(pluginExecution2);
return pluginExecution2;
});
if (Objects.isNull(pluginExecution.getGoals())) {
pluginExecution.setGoals(new ArrayList<>());
}
if (!pluginExecution
.getGoals()
.contains(JGitverAttachModifiedPomsMojo.GOAL_ATTACH_MODIFIED_POMS)) {
pluginExecution.getGoals().add(JGitverAttachModifiedPomsMojo.GOAL_ATTACH_MODIFIED_POMS);
}
if (Objects.isNull(plugin.getDependencies())) {
plugin.setDependencies(new ArrayList<>());
}
Optional<Dependency> dependencyOptional =
plugin.getDependencies().stream()
.filter(
x ->
JGitverUtils.EXTENSION_GROUP_ID.equalsIgnoreCase(x.getGroupId())
&& JGitverUtils.EXTENSION_ARTIFACT_ID.equalsIgnoreCase(x.getArtifactId()))
.findFirst();
dependencyOptional.orElseGet(
() -> {
Dependency dependency = new Dependency();
dependency.setGroupId(JGitverUtils.EXTENSION_GROUP_ID);
dependency.setArtifactId(JGitverUtils.EXTENSION_ARTIFACT_ID);
dependency.setVersion(pluginVersion.toString());
plugin.getDependencies().add(dependency);
return dependency;
});
}
}