forked from mojohaus/versions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CompareDependenciesMojo.java
484 lines (443 loc) · 18.9 KB
/
CompareDependenciesMojo.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
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 javax.inject.Inject;
import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.repository.RepositorySystem;
import org.codehaus.mojo.versions.api.ArtifactAssociation;
import org.codehaus.mojo.versions.api.PomHelper;
import org.codehaus.mojo.versions.api.Property;
import org.codehaus.mojo.versions.api.PropertyVersions;
import org.codehaus.mojo.versions.api.VersionsHelper;
import org.codehaus.mojo.versions.api.recording.ChangeRecord;
import org.codehaus.mojo.versions.api.recording.ChangeRecorder;
import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader;
import org.codehaus.mojo.versions.utils.DependencyBuilder;
import static java.util.Collections.singletonList;
/**
* Compare dependency versions of the current project to dependencies or dependency management of a remote repository
* project. Can optionally update locally the project instead of reporting the comparison
*
* @author Paul Gier
* @since 1.3
*/
@Mojo( name = "compare-dependencies", threadSafe = true )
public class CompareDependenciesMojo
extends AbstractVersionsDependencyUpdaterMojo
{
/**
* The width to pad info messages.
*
* @since 1.0-alpha-1
*/
private static final int INFO_PAD_SIZE = 68;
/**
* The groupId, artifactId, and version of the remote project (POM) to which we are comparing. This should be in the
* form "groupId:artifactId:version"
*/
@Parameter( property = "remotePom", required = true )
protected String remotePom;
/**
* Ignore the list of remote dependencies and only compare the remote dependencyManagement
*/
@Parameter( property = "ignoreRemoteDependencies", defaultValue = "false" )
protected boolean ignoreRemoteDependencies;
/**
* Ignore the remote dependency management and only check against the actual dependencies of the remote project
*/
@Parameter( property = "ignoreRemoteDependencyManagement", defaultValue = "false" )
protected boolean ignoreRemoteDependencyManagement;
/**
* Update dependency versions in the current POM.
*/
@Parameter( property = "updateDependencies", defaultValue = "false" )
protected boolean updateDependencies;
/**
* Update dependency versions stored in properties
*/
@Parameter( property = "updatePropertyVersions", defaultValue = "false" )
protected boolean updatePropertyVersions;
/**
* Display the dependency version differences on the command line, but do not update the versions in the current
* pom. If updateDependencies is set to "true" this will automatically be set to false.
*/
@Parameter( property = "reportMode", defaultValue = "true" )
protected boolean reportMode;
/**
* If the output file is set, the diff report will be written to this file.
*/
@Parameter( property = "reportOutputFile" )
protected File reportOutputFile;
/**
* The project builder used to initialize the remote project.
*/
protected MavenProjectBuilder mavenProjectBuilder;
// ------------------------------ METHODS --------------------------
@Inject
public CompareDependenciesMojo( RepositorySystem repositorySystem,
org.eclipse.aether.RepositorySystem aetherRepositorySystem,
WagonManager wagonManager,
ArtifactResolver artifactResolver,
MavenProjectBuilder mavenProjectBuilder,
Map<String, ChangeRecorder> changeRecorders )
{
super( repositorySystem, aetherRepositorySystem, wagonManager, artifactResolver,
changeRecorders );
this.mavenProjectBuilder = mavenProjectBuilder;
}
/**
* @param pom the pom to update.
* @throws org.apache.maven.plugin.MojoExecutionException Something wrong with the plugin itself
* @throws org.apache.maven.plugin.MojoFailureException The plugin detected an error in the build
* @throws javax.xml.stream.XMLStreamException when things go wrong with XML streaming
* @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader)
*/
protected void update( ModifiedPomXMLEventReader pom )
throws MojoExecutionException, MojoFailureException, XMLStreamException
{
if ( this.ignoreRemoteDependencies && this.ignoreRemoteDependencyManagement )
{
throw new MojoFailureException( " ignoreRemoteDependencies and ignoreRemoteDependencyManagement "
+ "are both set to true. At least one of these needs to be false " );
}
if ( updateDependencies )
{
reportMode = false;
}
String[] remotePomParts = this.remotePom.split( ":" );
if ( remotePomParts.length != 3 )
{
throw new MojoFailureException( " Invalid format for remotePom: " + remotePom );
}
String rGroupId = remotePomParts[0];
String rArtifactId = remotePomParts[1];
String rVersion = remotePomParts[2];
Artifact remoteArtifact = this.toArtifact( DependencyBuilder.newBuilder()
.withGroupId( rGroupId )
.withArtifactId( rArtifactId )
.withVersion( rVersion ).build() );
MavenProject remoteMavenProject = null;
try
{
remoteMavenProject =
mavenProjectBuilder.buildFromRepository( remoteArtifact, remoteArtifactRepositories, localRepository );
}
catch ( ProjectBuildingException e )
{
throw new MojoExecutionException( "Unable to build remote project " + remoteArtifact, e );
}
Map<String, Dependency> remoteDepsMap = new HashMap<>();
if ( !ignoreRemoteDependencyManagement )
{
List<Dependency> remoteProjectDepMgmtDeps = remoteMavenProject.getDependencyManagement() == null
? null
: remoteMavenProject.getDependencyManagement().getDependencies();
if ( remoteProjectDepMgmtDeps != null )
{
remoteProjectDepMgmtDeps.forEach( dep -> remoteDepsMap.putIfAbsent( dep.getManagementKey(), dep ) );
}
}
if ( !ignoreRemoteDependencies && remoteMavenProject.getDependencies() != null )
{
remoteMavenProject.getDependencies().forEach( dep ->
remoteDepsMap.putIfAbsent( dep.getManagementKey(), dep ) );
}
List<String> totalDiffs = new ArrayList<>();
List<String> propertyDiffs = new ArrayList<>();
if ( getProject().getDependencyManagement() != null && isProcessingDependencyManagement() )
{
totalDiffs.addAll(
compareVersions( pom, getProject().getDependencyManagement().getDependencies(), remoteDepsMap,
ChangeRecord.ChangeKind.DEPENDENCY_MANAGEMENT ) );
}
if ( getProject().getDependencies() != null && isProcessingDependencies() )
{
totalDiffs.addAll( compareVersions( pom, getProject().getDependencies(), remoteDepsMap,
ChangeRecord.ChangeKind.DEPENDENCY ) );
}
if ( updatePropertyVersions )
{
Map<Property, PropertyVersions> versionProperties =
this.getHelper().getVersionPropertiesMap( VersionsHelper.VersionPropertiesMapRequest.builder()
.withMavenProject( getProject() ).build() );
propertyDiffs.addAll( updatePropertyVersions( pom, versionProperties, remoteDepsMap ) );
}
if ( getProject().getParent() != null
&& remoteMavenProject.getParent() != null
&& isProcessingParent() )
{
Dependency parent = DependencyBuilder.newBuilder()
.withGroupId( remoteMavenProject.getParentArtifact().getGroupId() )
.withArtifactId( remoteMavenProject.getParentArtifact().getArtifactId() )
.withVersion( remoteMavenProject.getParentArtifact().getVersion() )
.withType( remoteMavenProject.getParentArtifact().getType() )
.withScope( remoteMavenProject.getParentArtifact().getScope() )
.withClassifier( remoteMavenProject.getParentArtifact().getClassifier() )
.build();
if ( getLog().isDebugEnabled() )
{
getLog().debug( "Processing parent dependency: " + parent );
}
remoteDepsMap.putIfAbsent( parent.getManagementKey(), parent );
totalDiffs.addAll( compareVersions( pom, singletonList( getParentDependency() ), remoteDepsMap,
ChangeRecord.ChangeKind.PARENT ) );
}
if ( reportMode )
{
getLog().info( "The following differences were found:" );
if ( totalDiffs.size() == 0 )
{
getLog().info( " none" );
}
else
{
for ( String totalDiff : totalDiffs )
{
getLog().info( " " + totalDiff );
}
}
getLog().info( "The following property differences were found:" );
if ( propertyDiffs.size() == 0 )
{
getLog().info( " none" );
}
else
{
for ( String propertyDiff : propertyDiffs )
{
getLog().info( " " + propertyDiff );
}
}
}
if ( reportOutputFile != null )
{
writeReportFile( totalDiffs, propertyDiffs );
}
}
/**
* Compare the dependency versions of the current project with the dependency versions of a remote project
*
* @throws XMLStreamException
*/
private List<String> compareVersions( ModifiedPomXMLEventReader pom, List<Dependency> dependencies,
Map<String, Dependency> remoteDependencies,
ChangeRecord.ChangeKind changeKind )
throws MojoExecutionException, XMLStreamException
{
List<String> updates = new ArrayList<>();
for ( Dependency dep : dependencies )
{
Artifact artifact = this.toArtifact( dep );
if ( !isIncluded( artifact ) )
{
continue;
}
Dependency remoteDep = remoteDependencies.get( dep.getManagementKey() );
if ( remoteDep != null )
{
String remoteVersion = remoteDep.getVersion();
if ( !dep.getVersion().equals( remoteVersion ) )
{
StringBuilder buf = writeDependencyDiffMessage( dep, remoteVersion );
updates.add( buf.toString() );
if ( !reportMode )
{
updateDependencyVersion( pom, dep, remoteVersion, changeKind );
}
}
}
}
return updates;
}
/**
* Updates the properties holding a version if necessary.
*/
private List<String> updatePropertyVersions( ModifiedPomXMLEventReader pom,
Map<Property, PropertyVersions> versionProperties,
Map<String, Dependency> remoteDependencies )
throws XMLStreamException
{
List<String> result = new ArrayList<>();
for ( Map.Entry<Property, PropertyVersions> entry : versionProperties.entrySet() )
{
Property property = entry.getKey();
PropertyVersions version = entry.getValue();
String candidateVersion = computeCandidateVersion( remoteDependencies, property, version );
if ( candidateVersion != null )
{
String originalVersion = version.getAssociations()[0].getArtifact().getVersion(); // Yekes
if ( !candidateVersion.equals( originalVersion ) ) // Update needed
{
result.add( writeDiffMessage( property.getName(), originalVersion, candidateVersion ).toString() );
if ( !reportMode
&& PomHelper.setPropertyVersion( pom, null, property.getName(), candidateVersion ) )
{
getLog().info( "Updated ${" + property.getName() + "} from " + originalVersion + " to "
+ candidateVersion );
}
}
}
}
return result;
}
/**
* Returns the candidate version to use for the specified property.
* <p/>
* The dependencies currently linked to the property must all be defined by the remote POM and they should refer to
* the same version. If that's the case, that same version is returned. Otherwise, <tt>null</tt> is returned
* indicating that there is no candidate.
*
* @param remoteDependencies the remote dependencies
* @param property the property to update
* @param propertyVersions the association
* @return the candidate version or <tt>null</tt> if there isn't any
*/
private String computeCandidateVersion( Map<String, Dependency> remoteDependencies, Property property,
PropertyVersions propertyVersions )
{
String candidateVersion = null;
for ( ArtifactAssociation artifactAssociation : propertyVersions.getAssociations() )
{
String id = generateId( artifactAssociation.getArtifact() );
Dependency dependency = remoteDependencies.get( id );
if ( dependency == null )
{
getLog().info( "Not updating ${" + property.getName() + "}: no info for " + id );
return null;
}
else
{
if ( candidateVersion == null )
{
candidateVersion = dependency.getVersion();
}
else if ( !candidateVersion.equals( dependency.getVersion() ) )
{
getLog().warn( "Could not update ${" + property.getName() + "}: version mismatch" );
return null;
}
}
}
return candidateVersion;
}
private void writeReportFile( List<String> dependenciesUpdate, List<String> propertiesUpdate )
throws MojoExecutionException
{
if ( !reportOutputFile.getParentFile().exists() )
{
reportOutputFile.getParentFile().mkdirs();
}
try ( FileWriter fw = new FileWriter( reportOutputFile ); //
PrintWriter pw = new PrintWriter( fw ) )
{
pw.println( "The following differences were found:" );
pw.println();
if ( dependenciesUpdate.size() == 0 )
{
pw.println( " none" );
}
else
{
for ( String dependencyUpdate : dependenciesUpdate )
{
pw.println( " " + dependencyUpdate );
}
}
pw.println();
pw.println( "The following property differences were found:" );
pw.println();
if ( propertiesUpdate.size() == 0 )
{
pw.println( " none" );
}
else
{
for ( String propertyUpdate : propertiesUpdate )
{
pw.println( " " + propertyUpdate );
}
}
}
catch ( IOException e )
{
throw new MojoExecutionException( "Unable to write report file. ", e );
}
}
/**
* Create a simple message describing the version diff
*
* @param dep
* @param remoteVersion
* @return The message
*/
private StringBuilder writeDependencyDiffMessage( Dependency dep, String remoteVersion )
{
String id = dep.getGroupId() + ":" + dep.getArtifactId();
return writeDiffMessage( id, dep.getVersion(), remoteVersion );
}
private StringBuilder writeDiffMessage( String id, String originalVersion, String targetVersion )
{
StringBuilder buf = new StringBuilder();
buf.append( id );
buf.append( ' ' );
int padding = INFO_PAD_SIZE - originalVersion.length() - targetVersion.length() - 4;
while ( buf.length() < padding )
{
buf.append( '.' );
}
buf.append( ' ' );
buf.append( originalVersion );
buf.append( " -> " );
buf.append( targetVersion );
return buf;
}
/**
* Creates a key that is similar to what {@link Dependency#getManagementKey()} generates for a dependency.
*/
private static String generateId( Artifact artifact )
{
StringBuilder sb = new StringBuilder();
sb.append( artifact.getGroupId() ).append( ":" ).append( artifact.getArtifactId() ).append( ":" )
.append( artifact.getType() );
if ( artifact.getClassifier() != null )
{
sb.append( ":" ).append( artifact.getClassifier() );
}
return sb.toString();
}
}