-
Notifications
You must be signed in to change notification settings - Fork 267
/
DisplayPluginUpdatesMojo.java
1803 lines (1669 loc) · 72.7 KB
/
DisplayPluginUpdatesMojo.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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.codehaus.mojo.versions;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import org.apache.maven.BuildFailureException;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.RuntimeInformation;
import org.apache.maven.lifecycle.Lifecycle;
import org.apache.maven.lifecycle.LifecycleExecutionException;
import org.apache.maven.lifecycle.LifecycleExecutor;
import org.apache.maven.lifecycle.mapping.LifecycleMapping;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.Prerequisites;
import org.apache.maven.model.Profile;
import org.apache.maven.model.ReportPlugin;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.apache.maven.plugin.InvalidPluginException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.PluginManagerException;
import org.apache.maven.plugin.PluginNotFoundException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.version.PluginVersionNotFoundException;
import org.apache.maven.plugin.version.PluginVersionResolutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.project.DefaultProjectBuilderConfiguration;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.interpolation.ModelInterpolationException;
import org.apache.maven.project.interpolation.ModelInterpolator;
import org.apache.maven.settings.Settings;
import org.codehaus.mojo.versions.api.ArtifactVersions;
import org.codehaus.mojo.versions.api.PomHelper;
import org.codehaus.mojo.versions.ordering.MavenVersionComparator;
import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader;
import org.codehaus.mojo.versions.utils.PluginComparator;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.ReaderFactory;
import org.codehaus.plexus.util.StringUtils;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Pattern;
/**
* Displays all plugins that have newer versions available, taking care of Maven version prerequisites.
*
* @author Stephen Connolly
* @since 1.0-alpha-1
*/
@Mojo( name = "display-plugin-updates", requiresProject = true, requiresDirectInvocation = false, threadSafe = true )
public class DisplayPluginUpdatesMojo
extends AbstractVersionsDisplayMojo
{
// ------------------------------ FIELDS ------------------------------
/**
* The width to pad warn messages.
*
* @since 1.0-alpha-1
*/
private static final int WARN_PAD_SIZE = 65;
/**
* The width to pad info messages.
*
* @since 1.0-alpha-1
*/
private static final int INFO_PAD_SIZE = 68;
/**
* String to flag a plugin version being forced by the super-pom.
*
* @since 1.0-alpha-1
*/
private static final String FROM_SUPER_POM = "(from super-pom) ";
/**
* @since 1.0-alpha-1
*/
@Component
private LifecycleExecutor lifecycleExecutor;
/**
* @since 1.0-alpha-3
*/
@Component
private ModelInterpolator modelInterpolator;
/**
* The plugin manager.
*
* @component
* @since 1.0-alpha-1
*/
@Component
private PluginManager pluginManager;
/**
* @since 1.3
*/
@Component
private RuntimeInformation runtimeInformation;
// --------------------- GETTER / SETTER METHODS ---------------------
/**
* Returns the pluginManagement section of the super-pom.
*
* @return Returns the pluginManagement section of the super-pom.
* @throws MojoExecutionException when things go wrong.
*/
private Map<String, String> getSuperPomPluginManagement()
throws MojoExecutionException
{
if ( new DefaultArtifactVersion( "3.0" ).compareTo( runtimeInformation.getApplicationVersion() ) <= 0 )
{
getLog().debug( "Using Maven 3.x strategy to determine superpom defined plugins" );
try
{
Method getPluginsBoundByDefaultToAllLifecycles =
LifecycleExecutor.class.getMethod( "getPluginsBoundByDefaultToAllLifecycles",
new Class[] { String.class } );
Set<Plugin> plugins =
(Set<Plugin>) getPluginsBoundByDefaultToAllLifecycles.invoke( lifecycleExecutor, new Object[] {
getProject().getPackaging() } );
// we need to provide a copy with the version blanked out so that inferring from super-pom
// works as for 2.x as 3.x fills in the version on us!
Map<String, String> result = new LinkedHashMap<>( plugins.size() );
for ( Plugin plugin : plugins )
{
result.put( plugin.getKey(), plugin.getVersion() );
}
URL superPom = getClass().getClassLoader().getResource( "org/apache/maven/model/pom-4.0.0.xml" );
if ( superPom != null )
{
try
{
try( Reader reader = ReaderFactory.newXmlReader( superPom ) )
{
StringBuilder buf = new StringBuilder( IOUtil.toString( reader ) );
ModifiedPomXMLEventReader pom = newModifiedPomXER( buf, superPom.toString() );
Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?"
+ "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin" );
Stack<StackState> pathStack = new Stack<>();
StackState curState = null;
while ( pom.hasNext() )
{
XMLEvent event = pom.nextEvent();
if ( event.isStartDocument() )
{
curState = new StackState( "" );
pathStack.clear();
}
else if ( event.isStartElement() )
{
String elementName = event.asStartElement().getName().getLocalPart();
if ( curState != null && pathRegex.matcher( curState.path ).matches() )
{
if ( "groupId".equals( elementName ) )
{
curState.groupId = pom.getElementText().trim();
continue;
}
else if ( "artifactId".equals( elementName ) )
{
curState.artifactId = pom.getElementText().trim();
continue;
}
else if ( "version".equals( elementName ) )
{
curState.version = pom.getElementText().trim();
continue;
}
}
pathStack.push( curState );
curState = new StackState( curState.path + "/" + elementName );
}
else if ( event.isEndElement() )
{
if ( curState != null && pathRegex.matcher( curState.path ).matches() )
{
if ( curState.artifactId != null )
{
Plugin plugin = new Plugin();
plugin.setArtifactId( curState.artifactId );
plugin.setGroupId( curState.groupId == null
? PomHelper.APACHE_MAVEN_PLUGINS_GROUPID
: curState.groupId );
plugin.setVersion( curState.version );
if ( !result.containsKey( plugin.getKey() ) )
{
result.put( plugin.getKey(), plugin.getVersion() );
}
}
}
curState = pathStack.pop();
}
}
}
}
catch ( IOException | XMLStreamException e )
{
// ignore
}
}
return result;
}
catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e1 )
{
// no much we can do here
}
}
getLog().debug( "Using Maven 2.x strategy to determine superpom defined plugins" );
Map<String, String> superPomPluginManagement;
try
{
MavenProject superProject =
projectBuilder.buildStandaloneSuperProject( new DefaultProjectBuilderConfiguration() );
superPomPluginManagement = new HashMap<>( getPluginManagement( superProject.getOriginalModel() ) );
}
catch ( ProjectBuildingException e )
{
throw new MojoExecutionException( "Could not determine the super pom.xml", e );
}
return superPomPluginManagement;
}
/**
* Gets the plugin management plugins of a specific project.
*
* @param model the model to get the plugin management plugins from.
* @return The map of effective plugin versions keyed by coordinates.
* @since 1.0-alpha-1
*/
private Map<String, String> getPluginManagement( Model model )
{
// we want only those parts of pluginManagement that are defined in this project
Map<String, String> pluginManagement = new HashMap<>();
try
{
for ( Plugin plugin : model.getBuild().getPluginManagement().getPlugins() )
{
String coord = plugin.getKey();
String version = plugin.getVersion();
if ( version != null )
{
pluginManagement.put( coord, version );
}
}
}
catch ( NullPointerException e )
{
// guess there are no plugins here
}
try
{
for ( Profile profile : model.getProfiles() )
{
try
{
for ( Plugin plugin : profile.getBuild().getPluginManagement().getPlugins() )
{
String coord = plugin.getKey();
String version = plugin.getVersion();
if ( version != null )
{
pluginManagement.put( coord, version );
}
}
}
catch ( NullPointerException e )
{
// guess there are no plugins here
}
}
}
catch ( NullPointerException e )
{
// guess there are no profiles here
}
return pluginManagement;
}
// ------------------------ INTERFACE METHODS ------------------------
// --------------------- Interface Mojo ---------------------
/**
* @throws MojoExecutionException when things go wrong
* @throws MojoFailureException when things go wrong in a very bad way
* @see AbstractVersionsUpdaterMojo#execute()
* @since 1.0-alpha-1
*/
public void execute()
throws MojoExecutionException, MojoFailureException
{
logInit();
Set<String> pluginsWithVersionsSpecified;
try
{
pluginsWithVersionsSpecified = findPluginsWithVersionsSpecified( getProject() );
}
catch ( XMLStreamException | IOException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
Map<String, String> superPomPluginManagement = getSuperPomPluginManagement();
getLog().debug( "superPom plugins = " + superPomPluginManagement );
List<MavenProject> parents = getParentProjects( getProject() );
Map<String, String> parentPlugins = getParentsPlugins( parents );
// TODO remove, not used any more (found while extracting getParentsPlugins method and
// renaming parentPluginManagement to parentPlugins)
// NOTICE: getProjectPlugins() takes profiles while getParentPlugins does not
// there is probably a little inconsistency (if plugins configured in profiles of parents)
Map<String, String> parentBuildPlugins = new HashMap<>();
Map<String, String> parentReportPlugins = new HashMap<>();
Set<Plugin> plugins = getProjectPlugins( superPomPluginManagement, parentPlugins, parentBuildPlugins,
parentReportPlugins, pluginsWithVersionsSpecified );
List<String> pluginUpdates = new ArrayList<>();
List<String> pluginLockdowns = new ArrayList<>();
ArtifactVersion curMavenVersion = runtimeInformation.getApplicationVersion();
ArtifactVersion specMavenVersion = MinimalMavenBuildVersionFinder.find( getProject(), "2.0", getLog() );
ArtifactVersion minMavenVersion = null;
boolean superPomDrivingMinVersion = false;
// if Maven prerequisite upgraded to a version, Map<plugin compact key, latest compatible plugin vesion>
Map<ArtifactVersion, Map<String, String>> mavenUpgrades = new TreeMap<>( new MavenVersionComparator() );
for ( Plugin plugin : plugins )
{
String groupId = plugin.getGroupId();
String artifactId = plugin.getArtifactId();
String version = plugin.getVersion();
String coords = ArtifactUtils.versionlessKey( groupId, artifactId );
if ( version == null )
{
version = parentPlugins.get( coords );
}
getLog().debug( "Checking " + coords + " for updates newer than " + version );
String effectiveVersion = version;
Artifact artifactRange;
try
{
boolean unspecified = ( version == null );
VersionRange versionRange = unspecified ? VersionRange.createFromVersionSpec( "[0,)" )
: VersionRange.createFromVersionSpec( version );
artifactRange = artifactFactory.createPluginArtifact( groupId, artifactId, versionRange );
}
catch ( InvalidVersionSpecificationException e )
{
throw new MojoExecutionException( "Invalid version range specification: " + version, e );
}
ArtifactVersion artifactVersion = null;
try
{
// now we want to find the newest versions and check their Maven version prerequisite
ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions( artifactRange, true );
ArtifactVersion[] newerVersions = artifactVersions.getVersions( this.allowSnapshots );
ArtifactVersion minRequires = null;
for ( int j = newerVersions.length - 1; j >= 0; j-- )
{
Artifact probe =
artifactFactory.createDependencyArtifact( groupId, artifactId,
VersionRange.createFromVersion( newerVersions[j].toString() ),
"pom", null, "runtime" );
try
{
getHelper().resolveArtifact( probe, true );
MavenProject pluginMavenProject =
projectBuilder.buildFromRepository( probe, remotePluginRepositories, localRepository );
ArtifactVersion pluginRequires = getPrerequisitesMavenVersion( pluginMavenProject );
if ( artifactVersion == null && compare( specMavenVersion, pluginRequires ) >= 0 )
{
// ok, newer version compatible with current specMavenVersion
artifactVersion = newerVersions[j];
}
if ( effectiveVersion == null && compare( curMavenVersion, pluginRequires ) >= 0 )
{
// version was unspecified, current version of maven thinks it should use this
effectiveVersion = newerVersions[j].toString();
}
if ( artifactVersion != null && effectiveVersion != null )
{
// no need to look at any older versions: latest compatible found
break;
}
// newer version not compatible with current specMavenVersion: track opportunity if Maven spec
// upgrade
if ( minRequires == null || compare( minRequires, pluginRequires ) > 0 )
{
Map<String, String> upgradePlugins =
mavenUpgrades.computeIfAbsent( pluginRequires, k -> new LinkedHashMap<>() );
String upgradePluginKey = compactKey( groupId, artifactId );
if ( !upgradePlugins.containsKey( upgradePluginKey ) )
{
String newer = newerVersions[j].toString();
if ( newer.equals( effectiveVersion ) )
{
// plugin version configured that require a Maven version higher than spec
upgradePlugins.put( upgradePluginKey,
pad( upgradePluginKey, INFO_PAD_SIZE, newer ) );
}
else
{
// plugin that can be upgraded
upgradePlugins.put( upgradePluginKey, pad( upgradePluginKey, INFO_PAD_SIZE,
effectiveVersion, " -> ", newer ) );
}
}
minRequires = pluginRequires;
}
}
catch ( ArtifactResolutionException | ArtifactNotFoundException | ProjectBuildingException e )
{
// ignore bad version
}
}
if ( effectiveVersion != null )
{
VersionRange currentVersionRange = VersionRange.createFromVersion( effectiveVersion );
Artifact probe = artifactFactory.createDependencyArtifact( groupId, artifactId, currentVersionRange,
"pom", null, "runtime" );
try
{
getHelper().resolveArtifact( probe, true );
MavenProject mavenProject =
projectBuilder.buildFromRepository( probe, remotePluginRepositories, localRepository );
ArtifactVersion requires = getPrerequisitesMavenVersion( mavenProject );
if ( minMavenVersion == null || compare( minMavenVersion, requires ) < 0 )
{
minMavenVersion = requires;
}
}
catch ( ArtifactResolutionException | ArtifactNotFoundException | ProjectBuildingException e )
{
// ignore bad version
}
}
}
catch ( ArtifactMetadataRetrievalException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
String newVersion;
if ( version == null && pluginsWithVersionsSpecified.contains( coords ) )
{
// Hack ALERT!
//
// All this should be re-written in a less "pom is xml" way... but it'll
// work for now :-(
//
// we have removed the version information, as it was the same as from
// the super-pom... but it actually was specified.
version = artifactVersion != null ? artifactVersion.toString() : null;
}
getLog().debug( "[" + coords + "].version=" + version );
getLog().debug( "[" + coords + "].artifactVersion=" + artifactVersion );
getLog().debug( "[" + coords + "].effectiveVersion=" + effectiveVersion );
getLog().debug( "[" + coords + "].specified=" + pluginsWithVersionsSpecified.contains( coords ) );
if ( version == null || !pluginsWithVersionsSpecified.contains( coords ) )
{
version = superPomPluginManagement.get( coords );
getLog().debug( "[" + coords + "].superPom.version=" + version );
newVersion = artifactVersion != null ? artifactVersion.toString()
: ( version != null ? version
: ( effectiveVersion != null ? effectiveVersion : "(unknown)" ) );
if ( version != null )
{
superPomDrivingMinVersion = true;
}
pluginLockdowns.add( pad( compactKey( groupId, artifactId ), WARN_PAD_SIZE,
superPomDrivingMinVersion ? FROM_SUPER_POM : "", newVersion ) );
}
else if ( artifactVersion != null )
{
newVersion = artifactVersion.toString();
}
else
{
newVersion = null;
}
if ( version != null && artifactVersion != null && newVersion != null && effectiveVersion != null
&& new DefaultArtifactVersion( effectiveVersion ).compareTo( new DefaultArtifactVersion( newVersion ) ) < 0 )
{
pluginUpdates.add( pad( compactKey( groupId, artifactId ), INFO_PAD_SIZE,
effectiveVersion, " -> ", newVersion ) );
}
}
// info on each plugin gathered: now it's time to display the result!
//
logLine( false, "" );
// updates keeping currently defined Maven version minimum
if ( pluginUpdates.isEmpty() )
{
logLine( false, "All plugins with a version specified are using the latest versions." );
}
else
{
logLine( false, "The following plugin updates are available:" );
for ( String update : new TreeSet<>(pluginUpdates) )
{
logLine( false, update );
}
}
logLine( false, "" );
// has every plugin a specified version?
if ( pluginLockdowns.isEmpty() )
{
logLine( false, "All plugins have a version specified." );
}
else
{
getLog().warn( "The following plugins do not have their version specified:" );
for ( String lockdown : new TreeSet<>(pluginLockdowns) )
{
getLog().warn( lockdown );
}
}
logLine( false, "" );
// information on minimum Maven version
boolean noMavenMinVersion = MinimalMavenBuildVersionFinder.find( getProject(), null, getLog() ) == null;
if ( noMavenMinVersion )
{
getLog().warn( "Project does not define minimum Maven version required for build, default is: 2.0" );
}
else
{
logLine( false, "Project requires minimum Maven version for build of: " + specMavenVersion );
}
logLine( false, "Plugins require minimum Maven version of: " + minMavenVersion );
if ( superPomDrivingMinVersion )
{
logLine( false, "Note: the super-pom from Maven " + curMavenVersion + " defines some of the plugin" );
logLine( false, " versions and may be influencing the plugins required minimum Maven" );
logLine( false, " version." );
}
logLine( false, "" );
if ( isMavenPluginProject() )
{
if ( noMavenMinVersion )
{
getLog().warn( "Project (which is a Maven plugin) does not define required minimum version of Maven." );
getLog().warn( "Update the pom.xml to contain" );
getLog().warn( " <prerequisites>" );
getLog().warn( " <maven><!-- minimum version of Maven that the plugin works with --></maven>" );
getLog().warn( " </prerequisites>" );
getLog().warn( "To build this plugin you need at least Maven " + minMavenVersion );
getLog().warn( "A Maven Enforcer rule can be used to enforce this if you have not already set one up" );
getLog().warn( "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html" );
}
else if ( minMavenVersion != null && compare( specMavenVersion, minMavenVersion ) < 0 )
{
getLog().warn( "Project (which is a Maven plugin) targets Maven " + specMavenVersion + " or newer" );
getLog().warn( "but requires Maven " + minMavenVersion + " or newer to build." );
getLog().warn( "This may or may not be a problem. A Maven Enforcer rule can help " );
getLog().warn( "enforce that the correct version of Maven is used to build this plugin." );
getLog().warn( "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html" );
}
else
{
logLine( false, "No plugins require a newer version of Maven than specified by the pom." );
}
}
else
{
if ( noMavenMinVersion )
{
logLine( true, "Project does not define required minimum version of Maven." );
logLine( true, "Update the pom.xml to contain maven-enforcer-plugin to" );
logLine( true, "force the Maven version which is needed to build this project." );
logLine( true, "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html" );
logLine( true, "Using the minimum version of Maven: " + minMavenVersion );
}
else if ( minMavenVersion != null && compare( specMavenVersion, minMavenVersion ) < 0 )
{
logLine( true, "Project requires an incorrect minimum version of Maven." );
logLine( true, "Update the pom.xml to contain maven-enforcer-plugin to" );
logLine( true, "force the Maven version which is needed to build this project." );
logLine( true, "See https://maven.apache.org/enforcer/enforcer-rules/requireMavenVersion.html" );
logLine( true, "Using the minimum version of Maven: " + specMavenVersion );
}
else
{
logLine( false, "No plugins require a newer version of Maven than specified by the pom." );
}
}
// updates if minimum Maven version is changed
for ( Map.Entry<ArtifactVersion, Map<String, String>> mavenUpgrade : mavenUpgrades.entrySet() )
{
ArtifactVersion mavenUpgradeVersion = mavenUpgrade.getKey();
Map<String, String> upgradePlugins = mavenUpgrade.getValue();
if ( upgradePlugins.isEmpty() || compare( specMavenVersion, mavenUpgradeVersion ) >= 0 )
{
continue;
}
logLine( false, "" );
logLine( false, "Require Maven " + mavenUpgradeVersion + " to use the following plugin updates:" );
for ( Map.Entry<String, String> entry : upgradePlugins.entrySet() )
{
logLine( false, entry.getValue() );
}
}
logLine( false, "" );
}
private static String pad( String start, int len, String...ends )
{
StringBuilder buf = new StringBuilder( len );
buf.append( " " );
buf.append( start );
int padding = len;
for ( String end : ends )
{
padding -= end.length();
}
buf.append( ' ' );
while ( buf.length() < padding )
{
buf.append( '.' );
}
buf.append( ' ' );
for ( String end : ends )
{
buf.append( end );
}
return buf.toString();
}
private Map<String, String> getParentsPlugins( List<MavenProject> parents )
throws MojoExecutionException
{
Map<String, String> parentPlugins = new HashMap<>();
for ( MavenProject parentProject : parents )
{
getLog().debug( "Processing parent: " + parentProject.getGroupId() + ":" + parentProject.getArtifactId()
+ ":" + parentProject.getVersion() + " -> " + parentProject.getFile() );
StringWriter writer = new StringWriter();
boolean havePom = false;
Model interpolatedModel;
try
{
Model originalModel = parentProject.getOriginalModel();
if ( originalModel == null )
{
getLog().warn( "project.getOriginalModel()==null for " + parentProject.getGroupId() + ":"
+ parentProject.getArtifactId() + ":" + parentProject.getVersion()
+ " is null, substituting project.getModel()" );
originalModel = parentProject.getModel();
}
try
{
new MavenXpp3Writer().write( writer, originalModel );
writer.close();
havePom = true;
}
catch ( IOException e )
{
// ignore
}
interpolatedModel =
modelInterpolator.interpolate( originalModel, null,
new DefaultProjectBuilderConfiguration().setExecutionProperties( getProject().getProperties() ),
false );
}
catch ( ModelInterpolationException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
if ( havePom )
{
try
{
Set<String> withVersionSpecified =
findPluginsWithVersionsSpecified( new StringBuilder( writer.toString() ), getSafeProjectPathInfo(parentProject) );
Map<String, String> map = getPluginManagement( interpolatedModel );
map.keySet().retainAll( withVersionSpecified );
parentPlugins.putAll( map );
map = getBuildPlugins( interpolatedModel, true );
map.keySet().retainAll( withVersionSpecified );
parentPlugins.putAll( map );
map = getReportPlugins( interpolatedModel, true );
map.keySet().retainAll( withVersionSpecified );
parentPlugins.putAll( map );
}
catch ( IOException | XMLStreamException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
}
else
{
parentPlugins.putAll( getPluginManagement( interpolatedModel ) );
parentPlugins.putAll( getBuildPlugins( interpolatedModel, true ) );
parentPlugins.putAll( getReportPlugins( interpolatedModel, true ) );
}
}
return parentPlugins;
}
private String getSafeProjectPathInfo(MavenProject project) {
File file = project.getFile();
if (file != null) {
return file.getAbsolutePath();
}
else {
// path is used only as information in error message, we can fallback to project artifact info here
return project.toString();
}
}
private boolean isMavenPluginProject()
{
return "maven-plugin".equals( getProject().getPackaging() );
}
private String compactKey( String groupId, String artifactId )
{
if ( PomHelper.APACHE_MAVEN_PLUGINS_GROUPID.equals( groupId ) )
{
// a core plugin... group id is not needed
return artifactId;
}
return groupId + ":" + artifactId;
}
private static final class StackState
{
private final String path;
private String groupId;
private String artifactId;
private String version;
public StackState( String path )
{
this.path = path;
}
public String toString()
{
return path + "[groupId=" + groupId + ", artifactId=" + artifactId + ", version=" + version + "]";
}
}
/**
* Returns a set of Strings which correspond to the plugin coordinates where there is a version specified.
*
* @param project The project to get the plugins with versions specified.
* @return a set of Strings which correspond to the plugin coordinates where there is a version specified.
*/
private Set<String> findPluginsWithVersionsSpecified( MavenProject project )
throws IOException, XMLStreamException
{
return findPluginsWithVersionsSpecified( PomHelper.readXmlFile( project.getFile() ), getSafeProjectPathInfo(project) );
}
/**
* Returns a set of Strings which correspond to the plugin coordinates where there is a version specified.
*
* @param pomContents The project to get the plugins with versions specified.
* @param path Path that points to the source of the XML
* @return a set of Strings which correspond to the plugin coordinates where there is a version specified.
*/
private Set<String> findPluginsWithVersionsSpecified( StringBuilder pomContents, String path )
throws IOException, XMLStreamException
{
Set<String> result = new HashSet<>();
ModifiedPomXMLEventReader pom = newModifiedPomXER( pomContents, path );
Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?"
+ "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin" );
Stack<StackState> pathStack = new Stack<>();
StackState curState = null;
while ( pom.hasNext() )
{
XMLEvent event = pom.nextEvent();
if ( event.isStartDocument() )
{
curState = new StackState( "" );
pathStack.clear();
}
else if ( event.isStartElement() )
{
String elementName = event.asStartElement().getName().getLocalPart();
if ( curState != null && pathRegex.matcher( curState.path ).matches() )
{
if ( "groupId".equals( elementName ) )
{
curState.groupId = pom.getElementText().trim();
continue;
}
else if ( "artifactId".equals( elementName ) )
{
curState.artifactId = pom.getElementText().trim();
continue;
}
else if ( "version".equals( elementName ) )
{
curState.version = pom.getElementText().trim();
continue;
}
}
pathStack.push( curState );
curState = new StackState( curState.path + "/" + elementName );
}
else if ( event.isEndElement() )
{
if ( curState != null && pathRegex.matcher( curState.path ).matches() )
{
if ( curState.artifactId != null && curState.version != null )
{
if ( curState.groupId == null )
{
curState.groupId = PomHelper.APACHE_MAVEN_PLUGINS_GROUPID;
}
result.add( curState.groupId + ":" + curState.artifactId );
}
}
curState = pathStack.pop();
}
}
return result;
}
// -------------------------- OTHER METHODS --------------------------
/**
* Get the minimum required Maven version of the given plugin
* Same logic as in https://github.com/apache/maven-plugin-tools/blob/c8ddcdcb10d342a5a5e2f38245bb569af5730c7c/maven-plugin-plugin/src/main/java/org/apache/maven/plugin/plugin/PluginReport.java#L711
* @param pluginProject the plugin for which to retrieve the minimum Maven version which is required
* @return The minimally required Maven version (never {@code null})
*/
private ArtifactVersion getPrerequisitesMavenVersion( MavenProject pluginProject ) {
Prerequisites prerequisites = pluginProject.getPrerequisites();
if (null == prerequisites) {
return new DefaultArtifactVersion("2.0");
}
String prerequisitesMavenValue = prerequisites.getMaven();
if (null == prerequisitesMavenValue) {
return new DefaultArtifactVersion("2.0");
}
return new DefaultArtifactVersion(prerequisitesMavenValue);
}
/**
* Gets the build plugins of a specific project.
*
* @param model the model to get the build plugins from.
* @param onlyIncludeInherited <code>true</code> to only return the plugins definitions that will be inherited by
* child projects.
* @return The map of effective plugin versions keyed by coordinates.
* @since 1.0-alpha-1
*/
private Map<String, String> getBuildPlugins( Model model, boolean onlyIncludeInherited )
{
Map<String, String> buildPlugins = new HashMap<>();
try
{
for ( Plugin plugin : model.getBuild().getPlugins() )
{
String coord = plugin.getKey();
String version = plugin.getVersion();
if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) )
{
buildPlugins.put( coord, version );
}
}
}
catch ( NullPointerException e )
{
// guess there are no plugins here
}
try
{
for ( Profile profile : model.getProfiles() )
{
try
{
for ( Plugin plugin : profile.getBuild().getPlugins() )
{
String coord = plugin.getKey();
String version = plugin.getVersion();
if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) )
{
buildPlugins.put( coord, version );
}
}
}
catch ( NullPointerException e )
{
// guess there are no plugins here
}
}
}
catch ( NullPointerException e )
{
// guess there are no profiles here
}
return buildPlugins;
}
/**
* Returns the Inherited of a {@link Plugin} or {@link ReportPlugin}
*
* @param plugin the {@link Plugin} or {@link ReportPlugin}
* @return the Inherited of the {@link Plugin} or {@link ReportPlugin}
* @since 1.0-alpha-1
*/
private static boolean getPluginInherited( Object plugin )
{